Extend the getLayoutServiceContext pipeline
You can enable/disable the out-of-the-box properties and add your own data to the context
object by extending the getLayoutServiceContext
pipeline provided by the Layout Service.
To extend the getLayoutServiceContext
pipeline:
-
Create a processor by extending the
JssGetLayoutServiceContextProcessor
base provided by Headless Services:NoteIf you want to make your extension available to consumers of the Layout Service outside of Headless Services, you can implement the
Sitecore.LayoutService.ItemRendering.Pipelines.GetLayoutServiceContext.IGetLayoutServiceContextProcessor
interface.RequestResponsec#public class ExampleContextExtension : Sitecore.JavaScriptServices.ViewEngine.LayoutService.Pipelines.GetLayoutServiceContext.JssGetLayoutServiceContextProcessor { public ExampleContextExtension(IConfigurationResolver configurationResolver) : base(configurationResolver) { } protected override void DoProcess(GetLayoutServiceContextArgs args, AppConfiguration application) { args.ContextData.Add("securityInfo", new { isAnonymous = !Sitecore.Context.User.IsAuthenticated }); } }
-
To patch and configure your processor, create a configuration patch for it, and configure the app(s) and/or route(s) that the processor must run for, as demonstrated in the following example:
RequestResponsexml<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"> <sitecore> <pipelines> <group groupName="layoutService"> <pipelines> <getLayoutServiceContext> <processor type="SitecoreJss.Examples.ExampleContextExtension, SitecoreJss.Examples" resolve="true"> <AllowedConfigurations hint="list"> <!-- Unless you change the Layout Service config used by your JSS app, this should always be present. --> <jss>jss</jss> </AllowedConfigurations> <Applications hint="list"> <!-- Restrict the JSS apps for which this processor will execute. --> <reactApp>JssReactWeb</reactApp> </Applications> <Routes hint="list"> <!-- Restrict the route items for which this processor will execute. IDs, item paths, and wildcard item paths are allowed. --> <services>/sitecore/content/JssReactWeb/Home/Services*</services> <portfolio>{BAD2C001-1746-4312-8422-B28806A1191E}</portfolio> </Routes> </processor> </getLayoutServiceContext> </pipelines> </group> </pipelines> </sitecore> </configuration>
-
To confirm the output of the modified context, call the Layout Service endpoint
http://{YOUR_SITECORE_HOST}/sitecore/api/layout/render/jss?item=/Services&sc_apikey={YOUR_API_KEY}
:RequestResponseshell"context": { "securityInfo": { "isAnonymous": true }, "pageEditing": false, "site": { "name":"JssReactWeb" }, "navigation": [ { "name":"Home", "path":"/", "children": [ { "name":"About", "path":"/about" }, { "name":"Portfolio", "path":"/portfolio" }, { "name":"Services", "path":"/services" } ] } ] }