Fetch layout data using a custom REST data fetcher

Version: 22.x

The JSS RestLayoutServiceConfig type accepts a dataFetcherResolver property. You can use this property to pass a custom data fetcher to your instance of the Layout Service. By default, the JSS REST Layout service uses the NativeDataFetcher.

To use a REST layout service with a custom data fetcher:

  1. In a layout-service.ts file, create an instance of the RestLayoutService class and provide the configuration object:

    • For JSS version 22.4 or later, use NativeDataFetcher:

      RequestResponse
      import { 
        NativeDataFetcher,
        NativeDataFetcherResponse,
        RestLayoutService,
        LayoutServiceData
      } from '@sitecore-jss/sitecore-jss';
      import config from './config';
      // define your custom data fetcher
      function dataFetcher(url: string, data?: RequestInit): Promise<NativeDataFetcherResponse<LayoutServiceData>> {
        return new NativeDataFetcher().fetch(url, data);
      }
      export const layoutService = new RestLayoutService({
        apiHost: config.sitecoreApiHost,
        apiKey: config.sitecoreApiKey,
        siteName: config.jssAppName,
        tracking: false, // if you wish to disable tracking
        // provide your custom data fetcher to the service instance
        dataFetcherResolver: () => dataFetcher
      });
    • For JSS version 22.3 or earlier, use AxiosDataFetcher:

      RequestResponse
      import { AxiosResponse } from 'axios';
      import { 
        AxiosDataFetcher,
        RestLayoutService,
        LayoutServiceData
      } from '@sitecore-jss/sitecore-jss';
      import config from './config';
      
      // define your custom data fetcher
      function dataFetcher(url: string, data?: unknown): Promise<AxiosResponse<LayoutServiceData>> {
        return new AxiosDataFetcher().fetch(url, data);
      }
      
      export const layoutService = new RestLayoutService({
        apiHost: config.sitecoreApiHost,
        apiKey: config.sitecoreApiKey,
        siteName: config.jssAppName,
        tracking: false, // if you wish to disable tracking
        // provide your custom data fetcher to the service instance
        dataFetcherResolver: () => dataFetcher
      });
      
  2. Import and use the new layout service:

    RequestResponse
    import { layoutService } from './layout-service';
    
    const language = 'en';
    const sitecoreRoutePath = '/styleguide';
    
    layoutService.fetchLayoutData(sitecoreRoutePath, language).then(data => {
         // do something with the data
    });

Do you have some feedback for us?

If you have suggestions for improving this article,