1

We want to render current sitecore item url in one of the sitecore nextjs component.

Just want to know if there is any API or any other correct way to do it?

3 Answers 3

2

You can use useSitecoreContext hook to read the item path(relative URL) in NextJS project.

import { useSitecoreContext } from '@sitecore-jss/sitecore-jss-nextjs';

const { sitecoreContext } = useSitecoreContext();
const relativeUrl = sitecoreContext?.itemPath as string;

console.log(relativeUrl);

Similarly you can also get language using sitecoreContext.language.

You can also retrieve the hostname through below code.

import { siteResolver } from 'lib/site-resolver';
var siteName = sitecoreContext?.site?.name as string;
var hostName = siteResolver.getByName(siteName).hostName;

Hope this helps!!! Let me know in case you face any issues.

2
  • We want to have full url e.g.scheme://target host name/path. Just like we get in MVC by using api. Above gives relative path only and also it will not work in buckets as well Commented Mar 27 at 10:13
  • @VinodChavan I have updated the code above to fetch hostname, language and relative URL. Using that you can create the complete URL. Hope this helps!!! Commented Mar 27 at 11:16
1

Using the useSitecoreContext you can get current sitecore item url in the sitecore nextjs component.

import { useSitecoreContext } from '@sitecore-jss/sitecore-jss-nextjs';

const CurrentItemUrl = () => {
  const { route } = useSitecoreContext();
  const currentUrl = route ? route.url : '';

  return <div>Current Item URL: {currentUrl}</div>;
};

export default CurrentItemUrl;

Hope this help!!

1
  • This is not working. It gives route.url as undefined Commented Mar 27 at 10:12
0

You can write the below code in the Layout.tsx file:

const currentUrl = typeof window !== 'undefined' ? window.location.href : '';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.