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)
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>