Prep Work
Before you get to far in, if you haven't already done so, I would recommend taking a quick read on Creating A Sitecore CDP Initialization Next.js Component. I go into depth on how to initialize a component to work with Sitecore CDP in a NextJs app.
I mention this because we'll be extending it to get the guestRef
. This unique identifier is critical in order to update any information that pertains to a visitor when updating their profile with PII (Personally Identifiable Information).
We Need Access To The Boxever Object
Now, I'm not going to show you how to update a guests data using the _boxeverq
object. My interest is solely how you can grab the guestRef
so we can invoke other backend API commands. To do that, we need to run the following bit of code where we can grab it from data.customer.ref
.
Boxever.browserShow(
Boxever.browser_id,
Boxever.client_key,
function (data: any) {
aGuestRef = data.customer.ref;
},
'json'
);
The thing is, Boxever
isn't available until after it's been loaded.
So within our htmlInject
variable that we setup last article, we're adding this bit of code to trigger an event when it's ready to be used.
// boxeverReady polls until Boxever is ready to be used. When it is, dispatch event "boxeverReady".
function boxeverReady() {
const event = new Event('boxeverReady');
if (typeof Boxever === 'undefined'){
setTimeout(boxeverReady, 200);
} else {
window.dispatchEvent(event);
}
}
// Determine when the DOM is loaded and when it is, run the boxeverReady function.
function docReady(fn) {
if (document.readyState === "complete" || document.readyState === "interactive") {
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
docReady(boxeverReady);
Now Onto The NextJs Component
Now that we know we will have Boxever
available to use, we can setup our JSX component. We need to wrap our code in a useEffect() so that we can access the window object, otherwise we can't get access to Boxever.
We'll setup a listener to wait for the boxeverReady
event to trigger and then grab our guestRef
.
const SitecoreCDPBase = (props: SitecoreCDPBaseProps): JSX.Element => {
useEffect(() => {
let aGuestRef = '';
const handleBoxeverLoad = () => {
const awindow = window as any; // Setup a new window as type any because Boxever is added at runtime.
const Boxever = awindow.Boxever; // Grab Boxever.
// Run code to grab the guestRef
Boxever.browserShow(
Boxever.browser_id,
Boxever.client_key,
function (data: any) {
aGuestRef = data.customer.ref;
},
'json'
);
};
window.addEventListener('boxeverReady', handleBoxeverLoad);
return () => {
// Unbind the event listener on clean up
document.removeEventListener('boxeverReady', handleBoxeverLoad);
};
}, []);
...
Now that you have the guestRef
you can run other Sitecore CDP guest data model functions.