Configure personalization in a Next.js JSS app

Version: 22.x

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:

  1. Configure environment variables.

  2. Exclude routes from personalization.

  3. Change the cookie domain.

  4. Change the Page View Events configuration.

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

  6. 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.

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

RequestResponse
NEXT_PUBLIC_COOKIE_DOMAIN=.mysite.com
Important

The change required here depends on the version of JSS you are using.

To change the cookie domain configuration:

  • For JSS 22.2+ and Cloud SDK 0.4+ - in the root directory of the Next.js application, in the src/Bootstrap.tsx file, replace the cookieDomain value in the initializer for CloudSDK:

    RequestResponse
    CloudSDK({
      sitecoreEdgeContextId: config.sitecoreEdgeContextId,
      siteName: props.site?.name || config.sitecoreSiteName,
      enableBrowserCookie: true,
      // Replace with the top-level cookie domain of the website that is being integrated e.g ".example.com" and not "www.example.com"
      cookieDomain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
    })
    .addEvents()
    .initialize();
  • For JSS 22.1 and earlier - 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: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
        // 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.

Important

The change required here depends on the version of JSS you are using.

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

  • 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 JSS 22.2+ and Cloud SDK 0.4+:

      RequestResponse
      pageView({
        channel: 'WEB',
        currency: 'EUR',
        page: route.name,
        pageVariantId,
        language,
      });
    • For JSS 22.1 and earlier:

      RequestResponse
      context.getSDK('Events').then((Events) =>
        Events.pageView({
          channel: 'WEB',
          currency: 'EUR',
          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.

Important

Disabling personalization will stop further data capture and cause your stored data to be automatically deleted after 30 days.

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.

Note

This only relates to page-level personalization. Variants for component-level A/B/n testing cannot be statically generated.

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,