Walkthrough: Configuring personalization in a Next.js JSS app

Current version: 22.0

When you create a Next.js application and include the Next.js XM Cloud add-on, or you use an XM Cloud Stater Kit, the add-on is preconfigured with working default values, but you might have to adjust the default configuration to fit your requirements.

This walkthrough describes how to:

  • Configure environment variables.

  • Exclude routes from personalization.

  • Change the cookie domain.

  • Change the Page View Events configuration.

  • Enable or disable the Personalize middleware and Page View event tracking.

  • Enable static generation for personalized variants.

Configure environment variables

The XM Cloud add-on uses environment variables for configurations related to the personalization middleware and page view events.

To configure environment variables:

  1. Make sure your site has a site identifier assigned to it.

  2. Find the Context ID of your XM Cloud environment.

  3. In your Next.js application, paste the value into the SITECORE_EDGE_CONTEXT_ID environment variable.

Exclude routes from personalization

The Personalize middleware excludes some routes from personalization by default, such as files, Next.js API routes, Sitecore API calls, and Next.js service calls.

Because the Personalize middleware runs on every request, you can improve your application's performance by excluding additional routes, preventing the middleware from requesting the page variants for those routes.

To exclude additional routes:

  • In the root directory of the Next.js application, in the src/lib/middleware/plugins/personalize.ts file, update the excludeRoute function to exclude the desired path name.

    For example:

    RequestResponse
    
    excludeRoute: (pathname: string) => {
      if (pathname.startsWith('/products')) {
        return true;
      }
      return false;
    }
    

The cookie domain is set by default in the Events SDK module to a transformed value of the current browser location host (window.location.host.replace(/^www\./, '')). You can replace the value in the file with a specific domain or an environment variable.

The Events SDK module is defined in the src/lib/context/sdk/events.ts file.

Assume you have defined an environment variable for your application as follows:

RequestResponse

NEXT_PUBLIC_COOKIE_DOMAIN=.mysite.com

To change the cookie domain configuration:

  • In the root directory of the Next.js application, in the src/lib/context/sdk/events.ts file, in the init function, in the Events SDK initializer, replace the cookieDomain value:

    RequestResponse
    
    await Events.init({
        siteName: props.siteName,
        sitecoreEdgeUrl: props.sitecoreEdgeUrl,
        sitecoreEdgeContextId: props.sitecoreEdgeContextId,
        // Replace with the top-level cookie domain of the website that is being integrated e.g ".example.com" and not "www.example.com"
        cookieDomain: window.location.hostname.replace(/^www\./, ''),
        // Cookie may be created in personalize middleware (server), but if not, we should create it here
        enableBrowserCookie: true,
    });
    

Change the Page View Events configuration

The Page View event configured in the CDP Page View component has a default configuration, such as the WEB channel and USD currency.

You can replace the default values with hard-coded values or environment variables.

For example, to change the currency settings for the Page View events:

  • In the root directory of the Next.js application, in the src/components/CdpPageView.tsx file, in the Page View event configuration, change the currency code to EUR. For example:

    RequestResponse
    
    context.getSDK('Events').then((Events) =>
      Events.pageView({
        channel: 'WEB',
        currency: 'USD',
        page: route.name,
        pageVariantId,
        language,
      })
    );
    

Enable or disable the Personalize middleware and Page View event tracking

The Next.js XM Cloud add-on comes with both the Personalize middleware and Page View events enabled by default to reduce the configuration requirements during the development phase of a project.

Personalization and event tracking likely depend on visitor consent and the resulting consent cookie in production.

To control personalization and/or event tracking based on visitor consent:

  1. Implement your cookie consent management solution of choice.

  2. Modify the enable/disable hooks for personalization and/or event tracking based on visitor consent and the resulting cookie.

    The enable/disable hooks are available in the following files:

    • In the src/lib/middleware/plugins/personalize.ts file - the disabled option for the Personalize middleware.

    • In the src/components/CdpPageView.tsx file - the disabled function in the CDP Page View component.

Enable static generation for personalized variants

Build-time static generation of personalized page variants is disabled by default for build performance considerations, but you can enable it if required.

To enable static generation of personalized page variants at build-time:

  • In the root directory of the Next.js application, in the src/lib/sitemap-fetcher/plugins/graphql-sitemap-service.ts file, edit the configuration of the GraphQL Sitemap Service and set the includePersonalizedRoutes option to true. For example:

    RequestResponse
    
    this._graphqlSitemapService = new MultisiteGraphQLSitemapService({
        clientFactory,
        sites: [...new Set(siteResolver.sites.map((site: SiteInfo) => site.name))],
        includePersonalizedRoutes: true,
    });
    

Do you have some feedback for us?

If you have suggestions for improving this article,