1. @sitecore-cloudsdk/events

@sitecore-cloudsdk/events/browser

Version:

The browser module provides the following functions to capture and send events from the browser side:

Function

Description

init

Initializes the module.

pageView

Sends a VIEW event.

identity

Sends an IDENTITY event.

form

Sends a FORM event.

event

Sends a custom event.

addToEventQueue

Adds events with a valid payload to the event queue.

processEventQueue

Sends all the events in the event queue, in the order they were added.

clearEventQueue

Empties the event queue without sending any of the events.

getBrowserId

Retrieves the browser ID.

getGuestId

Retrieves the guest ID.

init(settings)

This asynchronous function initializes the module. You must run this function before you can run any other functions in the module.

Parameters

Parameter

Type

Description

settings

settings object

Details about your SitecoreAI instance and cookie settings.

settings

Attribute

Type

Description

Example

Required/optional

sitecoreEdgeContextId

string (UUID)

Context ID.

Accessible and stored as an environment variable in your app.

"3axQRoRznWUqHR8B2RSbdo"

Required

siteName

string

The name of the site.

Accessible and stored as an environment variable in your app.

"myRetailSite"

Required

enableBrowserCookie

boolean

Flag to set cookies from the browser side.

The default is false.

If you're using both the browser and the server modules of this package, set the value for either enableBrowserCookie or enableServerCookie to true, and set the value for the other attribute to false.

true or false

Optional

cookieDomain

string

Your cookie domain.

The cookie domain is the top-level domain of your app. The cookie domain ensures that the Cloud SDK stores cookies in the web browser as first-party cookies.

The default is your domain.

You must set the same value for this attribute in every Cloud SDK module you initialize.

  • ".myretailsite.com"

  • ".beta.myretailsite.com"

  • "localhost"

Optional

cookieExpiryDays

integer

The number of days before the cookie expires.

If you don't set a value, the cookie expires according to the Max-Age that the browser sets.

You must set the same value for this attribute in every Cloud SDK module you initialize.

For example, set the value to 1 for the cookie to expire in 1 day.

Optional

cookiePath

string

A URL path that must exist in the requested URL in order to send the cookie.

The default is "/".

You must set the same value for this attribute in every Cloud SDK module you initialize.

"/"

Optional

Code examples

JSS Next.js

The JSS Next.js app automatically initializes this module in src/lib/context/sdk/events.ts.

Next.js

Here's an example page.tsx script showing how to initialize the module:

"use client";
import { useEffect } from "react";
import { init } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module ->
  useEffect(() => {
    initEvents();
  }, []);

  const initEvents = async () => {
    await init({
      sitecoreEdgeContextId: "<YOUR_CONTEXT_ID>",
      siteName: "<YOUR_SITE_NAME>",
      enableBrowserCookie: true,
    });

    console.log("Initialized the events/browser module.");
  };
  // <- Initialize the module

  return (<></>);
};

pageView([eventData])

This asynchronous function sends a VIEW event.

The VIEW event captures the site visitor's action of viewing a webpage in your app. It triggers every time your webpage loads. You must send VIEW events from all webpages where you want to track site visitor behavior.

JSS apps automatically capture VIEW events, with no coding required.

We recommend that you capture VIEW events on the following webpage types:

  • Home

  • Search results

  • Product description

  • Payment

  • Confirmation

  • Promotional offers

The VIEW event also lets you capture data such as the name of the page where the VIEW event triggered, the referrer URL, UTM parameters, and whether the page view triggered on a personalized page variant created in XM Cloud Pages Personalize.

Parameters

Parameter

Type

Description

Required/optional

eventData

eventData object

All the required and optional data about a VIEW event.

Optional

eventData

Use the following attributes when creating the eventData object for VIEW events:

Attribute

Type

Description

Example

Required/optional

channel

string (uppercase)

The touchpoint where the user interacts with your brand.

For example, for webpages, the channel is "WEB". For mobile app screens, the channel is "MOBILE_APP".

If you don't set a value, this attribute will not be part of the event data.

Must be one of:

  • "AIRPORT_KIOSK"

  • "BRANCH"

  • "CALL_CENTER"

  • "EMAIL"

  • "GDS"

  • "KIOSK"

  • "MOBILE_APP"

  • "MOBILE_WEB"

  • "SMS"

  • "OFFLINE"

  • "OTA"

  • "OTHER"

  • "WEB"

Optional

currency

string (uppercase ISO 4217)

The alphabetic currency code of the currency the user is using in your app.

For example, if the user selects Australian dollars as the currency on your website, the currency is "AUD".

If you don't set a value, this attribute will not be part of the event data.

  • "EUR"

  • "GBP"

  • "USD"

Optional

extensionData

object

Any custom data you want to collect about an event in addition to the values you provided in the other attributes in eventData.

This object can contain maximum 50 custom attributes of your choice.

Use a flat object structure. Nested objects will be automatically flattened, and keys will be renamed as necessary.

{ customKey: "customValue" }

Optional

includeUTMParameters

boolean

Specify whether to add every UTM parameter from the URL of the current webpage to the event object.

The default is true.

true or false

Optional

language

string (uppercase ISO 639)

The language the user is using your app in.

For example, if the user selects the Japanese language on your website, the language is "JA".

This is a custom value of your choice.

For browser-side events, the default value is inferred from the HTML lang attribute. If the HTML lang attribute is not specified, the default is an empty string.

  • "DE"

  • "EN"

  • "FR"

Optional

page

string

The name of the webpage where the interaction with your brand takes place.

This is a custom value of your choice.

For browser-side events, the default value for the root page of your website is Home Page. For other pages, the default value is inferred from the URL pathname.

  • "Home Page"

  • "home"

  • "contact-us.html"

Optional

pageVariantId

string

The ID of a personalized page variant.

"page_variant_3"

Optional

referrer

string or null

The URI of the webpage that linked to the webpage where the event was captured.

For browser-side events, if you don't set a value, it will be inferred from document.referrer. If document.referrer is an empty string, the value will be set to null.

  • "https://www.example.com/"

  • null

Optional

Code examples

Example 1. Running the pageView function on certain pages only

JSS Next.js

The JSS Next.js app automatically sends VIEW events from every webpage using the src/components/CdpPageView.tsx component. You can modify this component to send VIEW events from certain pages only.

Here's an example of how to send VIEW events from the /about webpage only. Update your existing code in src/components/CdpPageView.tsx by specifying the webpages you want tracked inside the return statement of the disabled function:

const enabledRoutes= ['/about'];  
const disabled = () => {
  return (
    process.env.NODE_ENV === 'development' || (route && enabledRoutes.indexOf(route.name) === -1)
  );
};
Example 2. Running the pageView function

Next.js

Here's an example of how to use the pageView function:

"use client";
import { useEffect } from "react";
import { init, pageView } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module using init()...

  // Send event:
  const sendPageViewEvent = async () => {
    await pageView();
    
    console.log("Sent VIEW event.");
  };

  return (
    <div>
      <button onClick={sendPageViewEvent}>send VIEW event</button>
    </div>
  );
};




Example 3. Event data object for a VIEW event

Here's an example eventData object:

let eventData: any = {
  language: "EN",
  page: "home",
  pageVariantId: "page_variant_3",
  extensionData: {customKey: "customValue"},
};

By default, VIEW events include UTM parameters. Consider the following URL:

https://myretailsite.com?utm_source=newsletter&utm_medium=email&utm_campaign=summer_sale&utm_term=running+shoes

When you send a VIEW event from the previous URL, the event data will contain all the UTM parameters:

{ 
  "language": "EN",
  "page": "home",
  "pageVariantId": "page_variant_3",
  "extensionData": "{'customKey': 'customValue'}",
  "utm_source": "newsletter",
  "utm_medium": "email",
  "utm_campaign": "summer_sale",
  "utm_term": "running shoes"
}


identity(eventData)

This asynchronous function sends an IDENTITY event.

The IDENTITY event is used to resolve the identity of an anonymous site visitor of your app and turn them into a known customer. When Sitecore CDP receives an IDENTITY event, it runs a linking algorithm to try to match guest data from separate guest profiles, based on your organization's identity rules. We recommend that you learn about identity resolution in Sitecore CDP before you start sending IDENTITY events.

You can optionally include personally identifiable information (PII), such as email, first name, and last name.

Parameters

Parameter

Type

Description

Required/optional

eventData

eventData object

All the required and optional data about an IDENTITY event. You can include personally identifiable information (PII) in this object.

Required

eventData

Use the following attributes when creating the eventData object for IDENTITY events:

Attribute

Type

Description

Example

Required/optional

channel

string (uppercase)

The touchpoint where the user interacts with your brand.

For example, for webpages, the channel is "WEB". For mobile app screens, the channel is "MOBILE_APP".

If you don't set a value, this attribute will not be part of the event data.

Must be one of:

  • "AIRPORT_KIOSK"

  • "BRANCH"

  • "CALL_CENTER"

  • "EMAIL"

  • "GDS"

  • "KIOSK"

  • "MOBILE_APP"

  • "MOBILE_WEB"

  • "SMS"

  • "OFFLINE"

  • "OTA"

  • "OTHER"

  • "WEB"

Optional

currency

string (uppercase ISO 4217)

The alphabetic currency code of the currency the user is using in your app.

For example, if the user selects Australian dollars as the currency on your website, the currency is "AUD".

If you don't set a value, this attribute will not be part of the event data.

  • "EUR"

  • "GBP"

  • "USD"

Optional

identifiers

array of objects

The identifiers that are used to identify the users of your app.

identifiers: [{
    "id": "123456",
    "provider": "BXLP"
}]

Required

extensionData

object

Any custom data you want to collect about an event in addition to the values you provided in the other attributes in eventData.

This object can contain maximum 50 custom attributes of your choice.

Use a flat object structure. Nested objects will be automatically flattened, and keys will be renamed as necessary.

{ customKey: "customValue" }

Optional

language

string (uppercase ISO 639)

The language the user is using your app in.

For example, if the user selects the Japanese language on your website, the language is "JA".

This is a custom value of your choice.

For browser-side events, the default value is inferred from the HTML lang attribute. If the HTML lang attribute is not specified, the default is an empty string.

  • "DE"

  • "EN"

  • "FR"

Optional

page

string

The name of the webpage where the interaction with your brand takes place.

This is a custom value of your choice.

For browser-side events, the default value for the root page of your website is Home Page. For other pages, the default value is inferred from the URL pathname.

  • "Home Page"

  • "home"

  • "contact-us.html"

Optional

email

string (lowercase recommended)

The email address of the guest.

"[email protected]"

Optional

title

string (title case)

The title of the guest.

  • "Miss"

  • "Mr"

  • "Mrs"

  • "Ms"

Optional

firstName

string (title case recommended)

The first name of the guest.

"Jane"

Optional

lastName

string (title case recommended)

The last name of the guest.

"Doe"

Optional

gender

string

The gender of the guest.

"female"

Optional

dob

string (ISO 8601)

The date of birth of the guest.

"1984-04-15"

Optional

mobile

string

The mobile number of the guest.

"+3531234567"

Optional

phone

string

The phone number of the guest.

"+3531234567"

Optional

street

array of strings (title case recommended)

The street address of the guest.

["Tara Street"]

Optional

city

string (title case recommended)

The city address of the guest.

"Dublin"

Optional

state

string (title case recommended)

The state address of the guest.

"Oregon"

Optional

country

string (uppercase ISO 3166-1 alpha-2)

The country address of the guest.

"IE"

Optional

postalCode

string

The postal code of the guest.

"D2"

Optional

The identifiers array of objects:

Attribute

Type

Description

Example

Required/optional

id

string

The unique guest identifier provided by your organization's identity system, such as a Customer Relationship Management (CRM) system.

"123456"

Required

provider

string

The name of your organization's identity system, external to XM Cloud, that provided the unique guest identifier.

"BXLP"

Required

expiryDate

string (ISO 8601)

The date the unique guest identifier expires. This is determined by your organization's identity system.

"2025-04-15T08:39:44.868Z"

Optional

Code examples

Example 4. Running the identity function

JSS Next.js

Here's an example of how to use the identity function:

import { useEffect } from "react";
import { context } from "lib/context";

// ...

useEffect(() => {
  context.getSDK("Events")?.then((Events) =>
    Events.identity({
      identifiers: [
        {
            id: "123456",
            provider: "BXLP"
        }
      ],
    })
  );
}, []);
Example 5. Running the identity function

Next.js

Here's an example of how to use the identity function:

"use client";
import { useEffect } from "react";
import { init, identity } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module using init()...

  // Send event:
  const sendIdentityEvent = async () => {
    let eventData: any = {
      identifiers: [
          {
              id: "123456",
              provider: "BXLP"
          }
      ]
    };

    await identity(eventData);

    console.log("Sent IDENTITY event.");
  };

  return (
    <div>
      <button onClick={sendIdentityEvent}>send IDENTITY event</button>
    </div>
  );
};




Example 6. Event data object for an IDENTITY event

Here's an example eventData object:

let eventData: any = {
  channel: "WEB",
  currency: "EUR",
  email: "[email protected]",
  title: "Miss",
  firstName: "Jane",
  lastName: "Doe",
  gender: "female",
  dob: "1984-04-15",
  mobile: "+3531234567",
  phone: "+3531234567",
  street: ["Tara Street"],
  city: "Dublin",
  country: "IE",
  identifiers: [
    {
      id: "123456",
      provider: "BXLP",
    },
  ],
  extensionData: { customKey: "customValue" },
};


form(formId, interactionType)

This asynchronous function sends a FORM event.

The FORM event is used to capture a user interaction with XM Cloud forms, for example, when the user views or submits the form. Data entered in the form is not collected.

Note

FORM events can't be added to the event queue.

To capture and send behavioral data in a form not created in XM Cloud, you can send a custom event using the event function.

Parameters

Parameter

Type

Description

Example

Required/optional

formId

string (UUID)

The UUID of the XM Cloud form.

To find the form ID in XM Cloud Forms, click the form you want to work with, then click Settings. The form ID is in Form ID field.

"0c0910e5-5197-4dcf-8993-677e70bcb531"

Required

interactionType

string (uppercase)

The interaction the user has with the form.

Must be one of:

  • "VIEWED"

  • "SUBMITTED"

Required

Code examples

JSS Next.js

The JSS Next.js app automatically captures FORM events.

Example 7. Running the form function

Next.js

Here's an example of how to use the form function:

"use client";
import { useEffect } from "react";
import { init, form } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module using init()...

  // Send event:
  const sendFormEvent = async () => {
    await form("0c0910e5-5197-4dcf-8993-677e70bcb531", "VIEWED");

    console.log("Sent FORM event.");
  };

  return (
    <div>
      <button onClick={sendFormEvent}>send FORM event</button>
    </div>
  );
};


event(eventData)

This asynchronous function sends a custom event with custom data of your choice.

Using a custom event, you can track any custom behavior of your choice, for example, a site visitor's action of clicking a component or adding a product item to their wish list.

Parameters

Parameter

Type

Description

Required/optional

eventData

eventData object

All the required and optional data about a custom event.

Required

eventData

Use the following attributes when creating the eventData object for custom events:

Attribute

Type

Description

Example

Required/optional

channel

string (uppercase)

The touchpoint where the user interacts with your brand.

For example, for webpages, the channel is "WEB". For mobile app screens, the channel is "MOBILE_APP".

If you don't set a value, this attribute will not be part of the event data.

Must be one of:

  • "AIRPORT_KIOSK"

  • "BRANCH"

  • "CALL_CENTER"

  • "EMAIL"

  • "GDS"

  • "KIOSK"

  • "MOBILE_APP"

  • "MOBILE_WEB"

  • "SMS"

  • "OFFLINE"

  • "OTA"

  • "OTHER"

  • "WEB"

Optional

currency

string (uppercase ISO 4217)

The alphabetic currency code of the currency the user is using in your app.

For example, if the user selects Australian dollars as the currency on your website, the currency is "AUD".

If you don't set a value, this attribute will not be part of the event data.

  • "EUR"

  • "GBP"

  • "USD"

Optional

extensionData

object

Any custom data you want to collect about an event in addition to the values you provided in the other attributes in eventData.

This object can contain maximum 50 custom attributes of your choice.

Use a flat object structure. Nested objects will be automatically flattened, and keys will be renamed as necessary.

{ customKey: "customValue" }

Optional

type

string

The type of the event. You can set this to any value of your choice that is not a reserved event name.

Reserved event names:

We recommend that you set this to a unique value by including, for example, your site name in the value.

"myretailsite:CLICKED_PROMO"

Required

Code examples

Example 8. Running the event function

JSS Next.js

Here's an example of how to use the event function to send a custom event named "myretailsite:CLICKED_PROMO":

import { useEffect } from "react";
import { context } from "lib/context";

// ...

useEffect(() => {
  context.getSDK("Events")?.then((Events) =>
    Events.event({
      type: "myretailsite:CLICKED_PROMO",
    })
  );
}, []);
Example 9. Running the event function

Next.js

Here's an example of how to use the event function to send a custom event named "myretailsite:CLICKED_PROMO":

"use client";
import { useEffect } from "react";
import { init, event } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module using init()...

  // Send event:
  const sendCustomEvent = async () => {
    let eventData: any = {
      type: "myretailsite:CLICKED_PROMO",
    };

    await event(eventData);

    console.log("Sent custom event.");
  };

  return (
    <div>
      <button onClick={sendCustomEvent}>send custom event</button>
    </div>
  );
};




Example 10. Event data object for a custom event

Here's an example eventData object:

let eventData: any = {
  channel: "WEB",
  currency: "EUR",
  type: "myretailsite:CLICKED_PROMO",
  extensionData: { customKey: "customValue" },
};


addToEventQueue(eventData)

This asynchronous function saves an event with a valid payload to the event queue. After you call this function, you can run the event queue using processEventQueue or empty it using clearEventQueue.

Note

FORM events can't be added to the event queue.

Parameters

Parameter

Type

Description

Required/optional

eventData

eventData object

All the required and optional data about an event.

Required

eventData

In the eventData object, you must specify the type of the event:

Attribute

Type

Description

Example

Required/optional

type

string

The type of the event, for example, "VIEW", "IDENTITY", or "myretailsite:CLICKED_PROMO".

  • "VIEW"

  • "IDENTITY"

  • "myretailsite:CLICKED_PROMO"

Required

To determine what other attributes you have to or optionally can include in the eventData object, see the eventData object applicable to the type of event you want to save to the event queue:

Code examples

Example 11. Running the addToEventQueue function

JSS Next.js

Here's an example of how to use the addToEventQueue function to save an event to the event queue.

import { useEffect } from "react";
import { context } from "lib/context";

// ...

useEffect(() => {
  context.getSDK("Events")?.then((Events) =>
    Events.addToEventQueue({
      type: "myretailsite:CLICKED_PROMO",
    })
  );
}, []);
Example 12. Running the addToEventQueue function

Next.js

Here's an example of how to use the addToEventQueue function to save events to the event queue.

In this scenario, we add different events to the event queue depending on whether a site visitor clicked a dropdown menu and a dropdown menu item.

In the following order, either the DROPDOWN_CLICK then the DROPDOWN_ITEM_CLICK events are added to the event queue, or the DROPDOWN_CLICK then the DROPDOWN_ABANDON events are added.

"use client";
import { useEffect } from "react";
import { init, addToEventQueue, processEventQueue } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module using init()...
  
  // Send events:
  const sendEvents = async () => {
    if (true) {
      await addToEventQueue({ type: "DROPDOWN_CLICK" });
      console.log("Added DROPDOWN_CLICK event to event queue.");

      if (true) {
        await addToEventQueue({ type: "DROPDOWN_ITEM_CLICK" });
        console.log("Added DROPDOWN_ITEM_CLICK event to event queue.");
      } else {
        await addToEventQueue({ type: "DROPDOWN_ABANDON" });
        console.log("Added DROPDOWN_ABANDON event to event queue.");
      }

      await processEventQueue();
      console.log("Sent all queued events.");
    }
  };

  return (
    <div>
      <button onClick={sendEvents}>send events</button>
    </div>
  );
};




processEventQueue()

This asynchronous function:

  • Runs the event queue, sending all the events that are in it.

  • Sends the events in the order they were added to the event queue.

  • Waits for a response from each event before it sends the next event.

Parameters

none

Code examples

Example 13. Running the processEventQueue function

JSS Next.js

Here's an example of how to use the processEventQueue function to run the event queue.

import { useEffect } from "react";
import { context } from "lib/context";

// ...

useEffect(() => {
  context.getSDK("Events")?.then((Events) =>
    Events.addToEventQueue({
      type: "myretailsite:CLICKED_PROMO",
    })
  );
}, []);

// ...

context.getSDK("Events").then((Event) => Events.processEventQueue());
Example 14. Running the processEventQueue function

Next.js

Here's an example of how to use the processEventQueue function to run the event queue.

In this scenario, we add different events to the event queue depending on whether a site visitor clicked a dropdown menu and a dropdown menu item.

When you run the event queue, either the DROPDOWN_CLICK then the DROPDOWN_ITEM_CLICK events are sent, or the DROPDOWN_CLICK then the DROPDOWN_ABANDON events.

"use client";
import { useEffect } from "react";
import { init, addToEventQueue, processEventQueue } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module using init()...
  
  // Send events:
  const sendEvents = async () => {
    if (true) {
      await addToEventQueue({ type: "DROPDOWN_CLICK" });
      console.log("Added DROPDOWN_CLICK event to event queue.");

      if (true) {
        await addToEventQueue({ type: "DROPDOWN_ITEM_CLICK" });
        console.log("Added DROPDOWN_ITEM_CLICK event to event queue.");
      } else {
        await addToEventQueue({ type: "DROPDOWN_ABANDON" });
        console.log("Added DROPDOWN_ABANDON event to event queue.");
      }

      await processEventQueue();
      console.log("Sent all queued events.");
    }
  };

  return (
    <div>
      <button onClick={sendEvents}>send events</button>
    </div>
  );
};




clearEventQueue()

This asynchronous function empties the event queue, removing all the events that are in it, without sending any of the events.

Parameters

none

Code examples

Example 15. Running the clearEventQueue function

JSS Next.js

Here's an example of how to use the clearEventQueue function to empty the event queue.

import { useEffect } from "react";
import { context } from "lib/context";

// ...

useEffect(() => {
  context.getSDK("Events")?.then((Events) =>
    Events.addToEventQueue({
      type: "myretailsite:CLICKED_PROMO",
    })
  );
}, []);

// ...

context.getSDK("Events").then((Event) => Events.clearEventQueue());
Example 16. Running the clearEventQueue function

Next.js

Here's an example of how to use the clearEventQueue function to empty the event queue.

In this scenario, we add different events to the event queue depending on whether a site visitor clicked a dropdown menu and a dropdown menu item.

If a certain condition is met, you decide to empty the event queue and not send any of the events you previously added to it.

"use client";
import { useEffect } from "react";
import { init, addToEventQueue, clearEventQueue } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module using init()...

  // Send events:
  const sendEvents = async () => {
    if (true) {
      await addToEventQueue({ type: "DROPDOWN_CLICK" });
      console.log("Added DROPDOWN_CLICK event to event queue.");

      if (true) {
        await addToEventQueue({ type: "DROPDOWN_ITEM_CLICK" });
        console.log("Added DROPDOWN_ITEM_CLICK event to event queue.");
      } else {
        await addToEventQueue({ type: "DROPDOWN_ABANDON" });
        console.log("Added DROPDOWN_ABANDON event to event queue.");
      }

      const timeout = true;
      if (timeout) {
        await clearEventQueue();
        console.log("Did not send any of the queued events.");
      }
    }
  };

  return (
    <div>
      <button onClick={sendEvents}>send events</button>
    </div>
  );
};




getBrowserId()

This function returns the browser ID, a UUID assigned to every site visitor. This function is used for testing and debugging purposes.

Parameters

none

Code examples

Example 17. Running the getBrowserId function

JSS Next.js

Here's an example of how to use the getBrowserId function to log the browser ID to the console:

import { useEffect } from "react";
import { context } from "lib/context";

// ...

useEffect(() => {
  context.getSDK("Events")?.then((Events) =>
    console.log("browser ID:", Events.getBrowserId());
  );
}, []);
Example 18. Running the getBrowserId function

Next.js

Here's an example of how to use the getBrowserId function to log the browser ID to the console:

"use client";
import { useEffect } from "react";
import { init, getBrowserId } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module:
  useEffect(() => {
    initEvents();
  }, []);

  const initEvents = async () => {
    await init({
      sitecoreEdgeContextId: "<context_id_PLACEHOLDER>",
      siteName: "<site_name_PLACEHOLDER>",
      enableBrowserCookie: true,
    });

    console.log("Initialized the events/browser module.");
    console.log("browser ID:", getBrowserId());
  };

  return (<></>);
};




getGuestId()

This function:

  • Lets you access the guest ID.

  • Returns a promise, so you have to await it to access the return value.

  • Is used for testing and debugging purposes.

Parameters

none

Code examples

Example 19. Running the getGuestId function

JSS Next.js

Here's an example of how to use the getGuestId function to log the guest ID to the console:

import { useEffect } from "react";
import { context } from "lib/context";

// ...

useEffect(() => {
  context.getSDK("Events")?.then((Events) => {
    Events.getGuestId().then((guestId) => console.log('guest ID:', guestId));
  });
}, []);
Example 20. Running the getGuestId function

Next.js

Here's an example of how to use the getGuestId function to log the guest ID to the console:

"use client";
import { useEffect } from "react";
import { init, getGuestId } from "@sitecore-cloudsdk/events/browser";

export default function Home() {
  // Initialize the module:
  useEffect(() => {
    initEvents();
  }, []);

  const initEvents = async () => {
    await init({
      sitecoreEdgeContextId: "<context_id_PLACEHOLDER>",
      siteName: "<site_name_PLACEHOLDER>",
      enableBrowserCookie: true,
    });

    console.log("Initialized the events/browser module.");

    const guestId = await getGuestId();
    console.log("guest ID:", guestId);
  };

  return (<></>);
};




If you have suggestions for improving this article, let us know!