Engage.initServer(settings)
The initServer()
function initializes the Engage SDK on the server side of your app. This function returns an object that contains the initServer.handleCookie()
function. After you call the initServer()
function, you must call the init()
function on the client side of your app.
You pass the same settings
object to both initServer()
and init()
, except that you don't specify the webPersonalization
attribute in initServer()
. That’s because the webPersonalization()
attribute is only available on the client side.
Here's an example of how to use the initServer()
function in a Next app. You must call the initServer()
function and save the return value into a variable.
pages/index.js
:
import { useEffect } from "react";
import { init, initServer } from "@sitecore/engage";
const engageSettings = {
// ...
forceServerCookieMode: true
};
const engageServer = initServer(engageSettings);
export async function getServerSideProps({ req, res }) {
await engageServer.handleCookie(req, res);
return {
props: {},
};
};
export default function Home() {
// ...
};
Note the following about the script:
-
In the settings object,
forceServerCookieMode
is set totrue
. This ensures that cookies are set from the server. -
The
engageServer
variable is assigned to the return value of theinitServer()
function. That givesengageServer
access to thehandleCookie()
function. -
The
handleCookie()
function creates cookies on the server and includes them in the response header.
Here's an example of how to receive the cookie from the server in a Next app and store the cookie in the web browser.
pages/index.js
:
export default function Home() {
const loadEngage = async () => {
// Load Engage API
const engage = await init({...engageSettings, webPersonalization: false /* boolean or object. See Settings object for all options. Default: false */ });
// Send VIEW events
};
useEffect(() => {
loadEngage();
}, []);
return (
<></>
);
};
In this script, the same settings
object is passed to the init()
function that was passed to the initServer()
function on the server side, except that the webPersonalization
attribute is specified only on the client side.
The client receives the header from the server and stores the cookie in the web browser.