Run JSS Next.js apps with GraphQL in disconnected mode

Abstract

Modify factories to return REST service instances when running disconnected

To use GraphQL, your JSS application must be connected to a Sitecore instance, because the disconnected development server only emulates REST services. Therefore, if you are running your JSS application in disconnected mode, the service factories must return a REST service.

You can use the environment variable JSS_MODE to distinguish between disconnected mode and other modes in your JavaScript code.

To return a REST service from your service factories:

  1. Modify the src/lib/layout-service-factory file so that, when running in disconnected mode, the LayoutServiceFactory class returns a RestLayoutService instance:

    import {
      LayoutService,
      GraphQLLayoutService,
      RestLayoutService,
      constants,
    } from '@sitecore-jss/sitecore-jss-nextjs';
    import config from 'temp/config';
    
    export class LayoutServiceFactory {
      create(): LayoutService {
        // Switch to REST endpoint if we are in disconnected mode
        if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
          return new RestLayoutService({
            apiHost: `http://localhost:${process.env.PROXY_PORT || 3042}`,
            apiKey: config.sitecoreApiKey,
            siteName: config.jssAppName,
          });
        }
    
        return new GraphQLLayoutService({
          endpoint: config.graphQLEndpoint,
          apiKey: config.sitecoreApiKey,
          siteName: config.jssAppName,
        });
      }
    }
    
    export const layoutServiceFactory = new LayoutServiceFactory();
  2. Modify the src/lib/dictionary-service-factory.ts, so, when running in disconnected mode, the DictionaryServiceFactory class return a RestDictionaryService instance:

    import {
      DictionaryService,
      RestDictionaryService,
      GraphQLDictionaryService,
      constants,
    } from '@sitecore-jss/sitecore-jss-nextjs';
    import config from 'temp/config';
    
    export class DictionaryServiceFactory {
      create(): DictionaryService {
        // Switch to REST endpoint if we are in disconnected mode
        if (process.env.JSS_MODE === constants.JSS_MODE.DISCONNECTED) {
          return new RestDictionaryService({
            apiHost: `http://localhost:${process.env.PROXY_PORT || 3042}`,
            apiKey: config.sitecoreApiKey,
            siteName: config.jssAppName,
          });
        }
    
        return new GraphQLDictionaryService({
          endpoint: config.graphQLEndpoint,
          apiKey: config.sitecoreApiKey,
          siteName: config.jssAppName,
        });
      }
    }
    
    export const dictionaryServiceFactory = new DictionaryServiceFactory();