Fetch layout data with the JSS REST Layout Service
One of the endpoints you can use to get layout data from Sitecore is the Sitecore Layout Service provided by Sitecore Headless Services using theRestLayoutService
class provided by JSS.
When using the Sitecore Layout Service, you can also enable (or disable) tracking of page views, by toggling the value for the tracking
property of the JSS REST Layout Service.
To invoke the Sitecore Layout Service from a JSS application using the JSS :
-
In a
layout-service.ts
file, import theRestLayoutService
class and your app configuration:RequestResponseimport { RestLayoutService } from '@sitecore-jss/sitecore-jss'; import config from './config';
-
Create an instance of
RestLayoutService
and provide the configuration object (of the typeRestLayoutServiceConfig
):RequestResponseexport const layoutService = new RestLayoutService({ apiHost: config.sitecoreApiHost, apiKey: config.sitecoreApiKey, siteName: config.jssAppName, // tracking: false // if you wish to disable tracking });
-
In the file where you want to fetch the data, import and use your new layout service instance:
RequestResponseimport { layoutService } from './layout-service'; const language = 'en'; const sitecoreRoutePath = '/styleguide'; layoutService.fetchLayoutData(sitecoreRoutePath, language).then(data => { // do something with the data });
If the default implementation does not meet your needs, you can use a custom data fetcher.