---
title: "Integrate a Next.js app using the Engage SDK package (server-set cookies)"
slug: "integrate-engage-sdk-nextjs-server-side"
abstract: "How to integrate a Next.js app with Sitecore CDP by installing the Engage SDK npm package and setting cookies from the server."
---
# Integrate a Next.js app using the Engage SDK package (server-set cookies)

> [!note]
> If your organization has a [JSS Next.js](https://doc.sitecore.com/sai/en/developers/jss/22/jss-sai/javascript-services-sdk--jss--for-next-js.html) or a JSS Angular application connected to SitecoreAI, implement Sitecore CDP\-related functionality on your SitecoreAI site using the [Sitecore Cloud SDK](https://doc.sitecore.com/sdk/en/developers/005/cloud-sdk/sitecore-cloud-sdk-for-javascript.html) instead. See also a [comparison of the Cloud SDK and the Engage SDK](https://doc.sitecore.com/sdk/en/developers/005/cloud-sdk/en/cloud-sdk-comparison-charts.html).

This topic explains how to integrate your Next.js app using the Engage SDK package. In this walkthrough, you'll use [server-set cookies](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/walkthroughs-for-integrating/cookies.html#UUID-706a7156-1d05-ac08-6a34-693f93415da6_section-idm4634652145412833300856510126 "Server-set cookies"). We assume that you are using the [`src` folder](https://nextjs.org/docs/app/building-your-application/configuring/src-directory), but you don't have to.

This walkthrough describes how to:

> [!note]
> **Before you begin**
> -   [Collect the required details](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/walkthroughs-for-integrating/collect-required-details.html "Collect required details") about your Sitecore CDP 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:

1. In your terminal, open the root folder of your Next.js app.
2. Install the Engage SDK by running the following command:

    ```shell
    npm install @sitecore/engage
    ```

3. In your code editor, open the root folder of your Next.js app.
4. In the `src` folder, create a file called `middleware.js`.
5. In `middleware.js` paste the following code:

    ```javascript
    import { NextResponse } from 'next/server';
    import { initServer } from '@sitecore/engage';

    export async function middleware(request) {
      const response = NextResponse.next();

      try {
        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);
      } catch (error) {
        console.error(error);
      }

      return response;
    };
    ```

    Replace the placeholder values with [the required details from your Sitecore CDP instance.](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/preparing-to-integrate/collect-required-details.html "Collect required details")

    > [!important]
    > **Cookie consent**
    > In production, only load the Engage SDK and set cookies if your site visitor grants consent. See also a [code example](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/walkthroughs-for-integrating/cookies.html "Cookies") to check if your site visitor accepts cookies.

    > [!important]
    > **Content Security Policy (CSP)**
    > To ensure that the Engage SDK script loads, you might have to add the following to your [Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP):
    >
    > -   Your [Stream API target endpoint](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/walkthroughs-for-integrating/collect-required-details.html#UUID-60c4c930-3cfe-e0ad-3b98-69ceff75989f_section-idm1903325950147122 "Stream API target endpoint").
    >
    > -   `https://d1mj578wat5n4o.cloudfront.net`
    >
    > -   If you run web personalization and your environment is **AP Region**, **EU Region**, or **US Region**:
    >
    > `https://d35vb5cccm4xzp.cloudfront.net`
    >
    > -   If you run web personalization and your environment is **JP Region**:
    >
    > `https://d2ez8k04aaol9g.cloudfront.net`

    This script:

    - Initializes the Engage SDK in a middleware function on the server using the `initServer()` function.
    - Collects the details about your Sitecore CDP instance and cookie settings in the `engageSettings` object, and passes the object to the `EngageServer.handleEngageCookie()` function.
    - Sets cookies from the server.

## Initialize `@sitecore/engage` on the client side

After 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:

1. Depending on your router type:
    - If using the *Pages Router* - in the `pages` folder, in the `index.js` file, import `useEffect` from React and `init` from `@sitecore/engage`:

        ```javascript
        import { useEffect } from "react";
        import { init } from "@sitecore/engage";
        ```

    - If using the *App Router* - in the `app` folder, in the `page.js` file, import `useEffect` from React and `init` from `@sitecore/engage`. Also, add the `"use client"` directive at the top of of the file, above all the imports:

        ```javascript
        "use client";
        import { useEffect } from "react";
        import { init } from "@sitecore/engage";
        ```

2. Above the `Home()` function, create an object called `engageSettings`:

    ```javascript
    const 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. Set to `false` if you don't have Personalize. */
    };
    ```

    Replace the placeholder values with [the required details from your Sitecore CDP instance.](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/preparing-to-integrate/collect-required-details.html "Collect required details")

3. In the `Home()` function, create an empty, asynchronous function `loadEngage()`, then call `loadEngage()` in an Effect Hook. You should use the Effect Hook because the `window` object has to be present before you load the Engage API. In the next procedure, you'll update the code inside `loadEngage()` to load the Engage API and start sending VIEW events.

    ```javascript
    export 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 CDP. You'll send a VIEW event because the VIEW event triggers every time your webpage loads.

To send a VIEW event:

1. In the `loadEngage()` function, load the Engage API by passing `engageSettings` to the `init()` function. The `init()` function is asynchronous, so you must await the return value.

    ```javascript
    const 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.

2. In the `loadEngage()` function, after you load the Engage API, call the `engage.pageView()` function to send VIEW event data:

    ```javascript
    const 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.](https://doc.sitecore.com/cdp/en/developers/api/stream-api/sitecore-engage-sdk-reference/objects/event-data-object/view-event.html "VIEW event")

3. In the `loadEngage()` function, below the `engage.pageView()` function, for testing and debugging purposes only, log the browser ID to the console:

    ```javascript
    const loadEngage = async () => {
      // Load Engage API
      // ...

      // Send VIEW events
      // ...

      // For testing and debugging purposes only
      console.log("Copy-paste the following line into Sitecore CDP > Guests > Search field:");
      console.log(engage.getBrowserId());
    };
    ```

    You'll use the browser ID in the next procedure to find the VIEW event in Sitecore CDP.

4. 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 CDP captured your VIEW event

After you have sent a VIEW event, you log in to Sitecore CDP and find the event.

To verify that Sitecore CDP captured your VIEW event:

1. In your web browser's console, find a text similar to:

    `a38b230c-11eb-4cf9-8d5d-274e9f344925​`

2. Copy the text.
3. In Sitecore CDP, click **Guests**, then in the search dropdown, select **Browser ID** and paste the copied text into the search field.

    An anonymous guest displays.

    ![Search field in the Guests screen.](https://doc.sitecore.com/api/markdown-image/cdp/en/developers/api/images/cdp-guests-bid.jpg)

    This guest is you loading your app just a minute ago. Next, you find the VIEW event associated with this guest.

4. Click the guest. The guest profile displays.
5. On the guest profile page, click **Event viewer**. A list of events associated with this guest displays. The list contains a VIEW event. This is the event that was triggered in the previous procedure.

## Next steps

You've now successfully integrated your app with Sitecore CDP. You sent an event from your app and verified that Sitecore CDP captures data about your users in real time.

Next, you can:

- [Send other behavioral data](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/understanding-integration-details/sending-events-using-the-engage-sdk.html "Sending events using the Engage SDK"), for example, an [IDENTITY event](https://doc.sitecore.com/cdp/en/developers/api/stream-api/sitecore-engage-sdk-reference/functions/engage-identity.html "Engage.identity(eventData[, extensionData])") or a [custom event](https://doc.sitecore.com/cdp/en/developers/api/stream-api/sitecore-engage-sdk-reference/functions/engage-event.html "Engage.event(type, eventData[, extensionData])").
- [Send transactional data](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/understanding-integration-details/sending-orders-using-the-engage-sdk.html "Sending orders using the Engage SDK") as the user interacts with products and shopping carts on your site.
- If you have Sitecore Personalize, you can [run experiences and experiments](https://doc.sitecore.com/cdp/en/developers/api/integrating-with-sitecore-cdp/understanding-integration-details/running-personalization.html "Running personalization").