In my layout.js file, I get the current URL of the page with this code:

url: typeof window !== 'undefined' ? window.location.href : '',

On first request of this page from the server, the url is set to ' ' since we have no window in the SSR of a page.

How can I get this information in the SSR?

  • We tried this to retrieve the canonical url but it failed. The workaround we did is to extend the layoutServiceContext to add the url. Commented Oct 14, 2019 at 10:20
  • Would you be willing to post the code ?
    – devzero
    Commented Oct 14, 2019 at 10:23

1 Answer 1


On first load, it is the NodeJS which is compiling the HTML Markup via the SSR. This is why the window is null. In order to have the url, I had to extend the LayoutServiceContext.

public class LayoutSiteContextExtension : IGetLayoutServiceContextProcessor
    public void Process(GetLayoutServiceContextArgs args)
        Assert.ArgumentNotNull(args, nameof(args));

        if (Context.Site == null)

        //Canonical URL
        if (!args.ContextData.ContainsKey("canonicalUrl"))
            var targetHostname = Context.Site.TargetHostName;

            var itemUrl = LinkManager.GetItemUrl(Context.Item);

            var canonicalUrl = itemUrl.Equals("/")
                ? $"{HttpContext.Current.Request.Url.Scheme}://{targetHostname}" 
                : $"{HttpContext.Current.Request.Url.Scheme}://{targetHostname}{itemUrl}";

            args.ContextData.Add("canonicalUrl", canonicalUrl);

Once you have implemented the above, you need to patch it with a config file as shown below

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/">
      <group groupName="layoutService">
            <processor type="Your Namespace, Your Assembly Name"
                       patch:after="processor[@type='Sitecore.LayoutService.ItemRendering.Pipelines.GetLayoutServiceContext.SiteContext, Sitecore.LayoutService']"/>
  • 1
    It's not obvious what to reference to get the IGetLayoutServiceContextProcessor, but I found it by doing "Install-Package sitecore.LayoutService", although you could probably just reference the sitecore.layoutservice dll
    – devzero
    Commented Oct 16, 2019 at 9:36
  • Also on the page you need to use: withSitecoreContext(), and you can then get the value from props.sitecoreContext.canonicalUrl
    – devzero
    Commented Oct 16, 2019 at 9:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.