Skip to main content

Sitecore

Extending Layout Service in Sitecore Headless

Istock 1440556661

Sitecore Headless uses a service called the Layout Service to deliver content from Sitecore to the front-end application in a headless architecture. It is responsible for rendering the layout of a page or a component and delivering the associated content to the client-side application.

The Layout Service constructs and delivers a JSON representation encompassing the context, route, placeholders, renderings (components), and data sources. This JSON payload fuels the rendering engine, enabling the rendering of the final user interface. While Sitecore Headless Services facilitates the exposure of endpoints to retrieve Sitecore route data in JSON format, it is essential to establish and configure a Sitecore Services Client (SSC) API key to interact with these endpoints. This ensures a secure and authenticated means of querying the Sitecore Headless Services for the required data.

For details on how to create an SSC API key, see Section 1.4 of this page. Once created, don’t forget to publish your API key if you use the API endpoint to query the Web database. Refer to this official doc for more details on Sitecore headless.

https://[siteUrl]/sitecore/api/layout/render/jss?item=[item ID or sitecore path]&sc_apikey=[your api key]

For Example:

https://sitecoreheadlesssc.dev.local/sitecore/api/layout/render/jss?item=/&sc_apikey={6E17D1A4-9A07-4A54-B32A-22BEC5B94847}

Out of the box, This returns the Context and Route objects if we want to add more fields in JSON; there is a way to extend this; let’s see how we can do this.

Note: The Layout Service output lacks inherent security and is susceptible to client-side inspection. Treat it as an open API, limit data to essentials for the front end, and avoid exposing sensitive details. For more details check out the official document Extending Layout Service.

Layout Service

Layout Service returns something like this:

Json Data

Sitecore has some predefined layout services pipeline config for GetLayoutServiceContext:

Layout Service Showconfig

It was apparent that it would be simple to add another pipeline processor that would add the data to the Context. Using LinkManager to get the item link for the context item and concat it with HOSTNAME, then patching the processor into the Layout Service pipeline required minimal code:

using Sitecore;
using Sitecore.Diagnostics;
using Sitecore.LayoutService.ItemRendering.Pipelines.GetLayoutServiceContext;
using Sitecore.Links;
using System;
using System.Collections.Generic;
using System.Web;

namespace Feature.Customization.PipelineProcessors
{
    public class ItemUrlContext : IGetLayoutServiceContextProcessor
    {
        public const string Key = "itemUrl";
        public void Process(GetLayoutServiceContextArgs args)
        {
            if (Context.Item !=  null)
            {
                Assert.ArgumentNotNull((object)args, nameof(args));
                IDictionary<string, object> contextData = args.ContextData;
                string link = LinkManager.GetItemUrl(Context.Item);

                var HostName = !String.IsNullOrWhiteSpace(Context.Site.TargetHostName) ? Context.Site.TargetHostName : HttpContext.Current.Request.Url.Host;

                var itemUrl = HostName + link;
                contextData.Add(Key, itemUrl);
            }
        }
    }
}

Layout Service Pipeline Patch

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <group groupName="layoutService">
        <pipelines>
          <getLayoutServiceContext>
            <processor type="Feature.Customization.PipelineProcessors.ItemUrlContext, Feature.Customization" />
          </getLayoutServiceContext>
        </pipelines>
      </group>
    </pipelines>
  </sitecore>
</configuration>

This resulted in the expected JSON output with an “itemUrl” property containing the URL of the context item.

Layoutservice Config

Updated Layout Service

Customization is crucial for unlocking unparalleled flexibility in extending Sitecore Headless Layout Service. From fine-tuning JSON output to incorporating personalized metadata, this journey empowers your headless architecture.

Special thanks to my awesome colleagues – Shivam Jain and Ashish Chinchkhede, for pairing and sharing this knowledge.

Stay tuned for more insights, and check out our Sitecore blog for more.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Ankit Tawale

Ankit Tawale is a Senior Technical Consultant at Perficient based in Nagpur. He is a Sitecore Certified Developer with experience in Sitecore, SXA, JavaScript, CSS, and .Net MVC. He is passionate about discovering new technology and understanding the architecture that supports them.

More from this Author

Categories
Follow Us