2

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. – Hishaam Namooya Oct 14 at 10:20
  • Would you be willing to post the code ? – devzero Oct 14 at 10:23
4

So, 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 an implementation that extend the LayoutServiceContext.

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

        if (Context.Site == null)
            return;

        //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/">
  <sitecore>
    <pipelines>
      <group groupName="layoutService">
        <pipelines>
          <getLayoutServiceContext>
            <processor type="Your Namespace, Your Assembly Name"
                       patch:after="processor[@type='Sitecore.LayoutService.ItemRendering.Pipelines.GetLayoutServiceContext.SiteContext, Sitecore.LayoutService']"/>
          </getLayoutServiceContext>
        </pipelines>
      </group>
    </pipelines>
  </sitecore>
</configuration>
  • 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 Oct 16 at 9:36
  • Also on the page you need to use: withSitecoreContext(), and you can then get the value from props.sitecoreContext.canonicalUrl – devzero Oct 16 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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