Integrate a Next.js app using the Engage SDK package (server-set cookies)
If your organization has a JSS Next.js or a JSS Angular application connected to Sitecore XM Cloud, implement Sitecore Personalize-related functionality on your XM Cloud site using the Sitecore Cloud SDK instead. See also a comparison of the Cloud SDK and the Engage SDK.
This topic explains how to integrate your Next.js app using the Engage SDK package. In this walkthrough, you'll use server-set cookies. We assume that you are using the src
folder, but you don't have to.
This walkthrough describes how to:
-
Install and initialize
@sitecore/engage
on the server side. -
Initialize
@sitecore/engage
on the client side. -
Send your first VIEW event.
-
Verify that Sitecore Personalize captured your VIEW event.
-
Collect the required details about your Sitecore Personalize instance.
-
Have a Next.js app to integrate. This walkthrough was tested on Next.js versions 12, 13, and 14.2.5, both for the Pages Router and the App Router.
Install and initialize @sitecore/engage on the server side
The first step to integrating your app is to install and initialize the @sitecore/engage
package in your web server. This step involves setting cookies from the server and sending them to the client.
To install and initialize the package on the server side:
-
In your terminal, open the root folder of your Next.js app.
-
Install the Engage SDK by running the following command:
RequestResponsenpm install @sitecore/engage
-
In your code editor, open the root folder of your Next.js app.
-
In the
src
folder, create a file calledmiddleware.js
. -
In
middleware.js
paste the following code:RequestResponseimport { NextResponse } from 'next/server'; import { initServer } from '@sitecore/engage'; export async function middleware(request) { const response = NextResponse.next(); const engageSettings = { clientKey: "<client_key_PLACEHOLDER>", targetURL: "<stream_api_target_endpoint_PLACEHOLDER>", pointOfSale: "<point_of_sale_PLACEHOLDER>", cookieDomain: "<cookie_domain_PLACEHOLDER>", cookieExpiryDays: 365, forceServerCookieMode: true }; const engageServer = initServer(engageSettings); await engageServer.handleCookie(request, response); return response; };
Replace the placeholder values with the required details from your Sitecore Personalize instance.
ImportantIn production, only load the Engage SDK and set cookies if your site visitor grants consent. See also a code example to check if your site visitor accepts cookies.
To ensure that the Engage SDK script loads, you might have to add
https://d1mj578wat5n4o.cloudfront.net
and your Stream API target endpoint to your Content Security Policy (CSP).This script:
-
Initializes the Engage SDK in a middleware function on the server using the
initServer()
function. -
Collects the details about your Sitecore Personalize instance and cookie settings in the
engageSettings
object, and passes the object to theEngageServer.handleEngageCookie()
function. -
Sets cookies from the server.
-
Initialize @sitecore/engage
on the client side
@sitecore/engage
on the client sideAfter you have installed and initialized the @sitecore/engage
package in your web server, you initialize the package on the client side. This step involves receiving cookies from the server and storing them in the web browser.
To initialize the package on the client side:
-
Depending on your router type:
-
If using the Pages Router - in the
pages
folder, in theindex.js
file, importuseEffect
from React andinit
from@sitecore/engage
:RequestResponseimport { useEffect } from "react"; import { init } from "@sitecore/engage";
-
If using the App Router - in the
app
folder, in thepage.js
file, importuseEffect
from React andinit
from@sitecore/engage
. Also, add the"use client"
directive at the top of of the file, above all the imports:RequestResponse"use client"; import { useEffect } from "react"; import { init } from "@sitecore/engage";
-
-
Above the
Home()
function, create an object calledengageSettings
:RequestResponseconst engageSettings = { clientKey: "<client_key_PLACEHOLDER>", targetURL: "<stream_api_target_endpoint_PLACEHOLDER>", pointOfSale: "<point_of_sale_PLACEHOLDER>", forceServerCookieMode: true, includeUTMParameters: true, webPersonalization: true /* boolean or object. See Settings object for all options. Default: false */ };
Replace the placeholder values with the required details from your Sitecore Personalize instance.
-
In the
Home()
function, create an empty, asynchronous functionloadEngage()
, then callloadEngage()
in an Effect Hook. You should use the Effect Hook because thewindow
object has to be present before you load the Engage API. In the next procedure, you'll update the code insideloadEngage()
to load the Engage API and start sending VIEW events.RequestResponseexport default function Home() { const loadEngage = async () => { // Load Engage API // Send VIEW events }; useEffect(() => { loadEngage(); }, []); return (<></>) };
Send your first VIEW event
Next, you update the code inside the loadEngage()
function to start collecting and sending data to Sitecore Personalize. You'll send a VIEW event because the VIEW event triggers every time your webpage loads.
To send a VIEW event:
-
In the
loadEngage()
function, load the Engage API by passingengageSettings
to theinit()
function. Theinit()
function is asynchronous, so you must await the return value.RequestResponseconst loadEngage = async () => { // Load Engage API const engage = await init(engageSettings); // Send VIEW events };
In production, you should call the
init()
function once, then share it across the app using the state management solution of your choice, for example, React Context or Redux. -
In the
loadEngage()
function, after you load the Engage API, call theengage.pageView()
function to send VIEW event data:RequestResponseconst loadEngage = async () => { // Load Engage API const engage = await init(engageSettings); // Send VIEW events engage.pageView({ channel: "<channel_PLACEHOLDER>", currency: "<currency_PLACEHOLDER>" }); };
Replace the placeholder values with the event details specific to your organization.
-
In the
loadEngage()
function, below theengage.pageView()
function, for testing and debugging purposes only, log the browser ID to the console:RequestResponseconst loadEngage = async () => { // Load Engage API // ... // Send VIEW events // ... // For testing and debugging purposes only console.log("Copy-paste the following line into Sitecore Personalize > Developer center > Event viewer > Search field:"); console.log(engage.getBrowserId()); };
You'll use the browser ID in the next procedure to find the VIEW event in Sitecore Personalize.
-
In your terminal, enter
npm run dev
to start your Next.js app. When the webpage loads, the VIEW event triggers and the event data is sent.
Verify that Sitecore Personalize captured your VIEW event
Next steps
You've now successfully integrated your app with Sitecore Personalize. You sent an event from your app and verified that Sitecore Personalize captures data about your users in real time.