Fetch layout data using a custom REST data fetcher

Version: 19.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 axios.

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:

    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,