Web UX Helper
Rokt UX Helper is an open source project that helps you render beautiful customer experiences in a server-to-server environment. You can find and contribute to the project on GitHub.
Overview
Rokt UX Helper leverages web components technology to provide a simple, maintainable solution for rendering Rokt experiences on your website. The rokt-layout-view custom element handles the rendering of experiences based on the payload received from your server.
Integration Steps
This document outlines the process for integrating Rokt UX Helper into your web project, which works alongside the Server-to-Server integration (S2S) to deliver relevant experiences to your customers as they checkout.
📦 Installation Guide
The library is available as an npm package. To install it, use the following commands:
npm install @rokt/ux-helper-web@stable
For testing new features, use @latest instead of @stable:
npm install @rokt/ux-helper-web@latest
🔹 Version Tags Explained
@stable: This tag points to the latest production-ready version of the library. It is recommended for applications that require stability and reliability.@latest: This tag points to the most recent version, including new features and improvements that may not yet be fully tested. Only use this for development and testing purposes to access the latest updates before they are officially marked as stable.
CDN Usage
If you prefer to use a CDN, you can include the library directly in your HTML:
<!-- Use the latest stable version -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.cjs"></script>
<!-- Or use the latest version with newest features -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web@latest/dist/index.cjs"></script>
The package also provides different module formats:
<!-- CommonJS format (for direct browser usage) -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.cjs"></script>
<!-- ESM format (for modern applications) -->
<script type="module">
import * as RoktUXHelper from 'https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.mjs';
</script>
Add rokt-layout-view
To start using Rokt UX Helper you need to add the bundled Rokt UX Helper script, add rokt-layout-view to the relevant part of your HTML view add your JavaScript.
<head>
<!-- Link to your Rokt UX Helper JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.cjs"></script>
</head>
<body>
<!-- Your content -->
<!-- Note the ID which is used in the JavaScript below -->
<rokt-layout-view id="rokt-layout-placeholder"></rokt-layout-view>
<!-- Your content -->
<!-- This is the JavaScript that handles events described below -->
<script src="./index.js"></script>
</body>
Register element and render the payload
Now you've added your rokt-layout-view you need to register it and pass in the payload to be rendered.
// This function would load the experiences data from your backend service or similar
const payload = fetchExperienceData();
const roktElement = document.getElementById("rokt-layout-placeholder");
roktElement.renderExperiences(payload);
// Note: The custom elements are automatically registered when the library is loaded,
// so you don't need to explicitly call registerCustomElements()
Handling overlay experiences
To support overlay experiences that target the body selector, add the render-overlay attribute:
<body>
<!-- Your content -->
<rokt-layout-view id="overlay" render-overlay></rokt-layout-view>
<!-- Your content -->
<script src="./index.js"></script>
</body>
Event Handling
Rokt UX Helper provides two types of events to help you track user interactions and communicate with the Rokt platform.
UX Events
Use UX Events to receive real-time feedback on user interactions:
roktElement.addEventListener('RoktUXEvent', (event) => {
// Use these events to tailor your user experience
console.log('RoktUXEvent received:', event.detail);
});
All UX Events
| Event | Description |
|---|---|
| OfferEngagement | Triggered when the user engages with the offer |
| PositiveEngagement | Triggered when the user positively engages with the offer |
| LayoutInteractive | Triggered when a layout is rendered and interactable |
| LayoutClosed | Triggered when a layout is closed by the user |
| LayoutCompleted | Triggered when the offer progression ends with no more offers to display |
| LayoutFailure | Triggered when a layout fails to display |
Platform Events
Platform events are essential for integration and must be sent to Rokt via your backend. These events return a full JSON payload with event data and integration details:
roktElement.addEventListener('RoktPlatformEvent', (event) => {
// Forward this payload to Rokt via your backend
fetch('/api/rokt-events', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event.detail)
});
});
Example Platform Event Payload
{
"events": [
{
"eventType": "SignalImpression",
"eventTime": "2024-12-05T04:42:54.683Z",
"sessionId": "b23d004d-b2e6-43e9-b254-d9193e650000",
"parentGuid": "9b6f0e5b-621d-4597-8a73-71d6a5b43a74",
"pageInstanceGuid": "b23d004d-b2e6-4b82-b7a2-84a13b6c57c5",
"metadata": [
{
"name": "clientTimeStamp",
"value": "2024-12-05T04:42:54.683Z"
},
{
"name": "captureMethod",
"value": "ClientProvided"
}
]
}
],
"integration": {
"name": "UX Helper Web",
"version": "1.0",
"framework": "JS",
"platform": "Web",
"layoutSchemaVersion": "1.3.0",
"deviceLocale": "en-GB",
"deviceModel": "Desktop Computer",
"deviceType": "Desktop",
"operatingSystem": "MacOS",
"operatingSystemVersion": "10.15.7",
"packageName": "UX Helper Web",
"packageVersion": "1.0"
},
"pluginId": "3333926045359669274"
}
For more details on Platform Events, refer to the API reference.
Sending Events to Layouts
You can also send events to the rendered layouts using the send method. This is useful for communicating with layouts based on actions in your application:
// Send a cart update event to all rendered layouts
await roktElement.send('V2_UPDATE_CART_ITEM', {
cartItemId: "item-123",
quantity: 2
});
This example sends a cart item update event that layouts can respond to, such as updating promotional offers based on quantities.
Summary
Integrating rokt-layout-view into your project is straightforward and provides a flexible way to manage views and experiments. By following the steps outlined in this guide, you can add rokt-layout-view into your project and take full advantage of the powerful features offered by Rokt UX Helper.
Complete Example
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Rokt UX Helper</title>
<link rel="stylesheet" href="./index.css" />
<!-- Load Rokt UX Helper from CDN -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.cjs"></script>
</head>
<body>
<h1>Rokt UX Helper Demo</h1>
<!-- Note the ID which is used in the JavaScript below -->
<!-- It is possible to use a single `rokt-layout-view` element to handle your embedded and overlay layouts -->
<rokt-layout-view
id="rokt-layout-placeholder"
render-overlay
></rokt-layout-view>
<script src="./index.js"></script>
</body>
</html>
JavaScript
// This function would load the experiences data from your backend service
const payload = fetchExperienceData();
const roktElement = document.getElementById("rokt-layout-placeholder");
roktElement.addEventListener("RoktUXEvent", (event) => {
console.log("RoktUXEvent received: ", event.detail);
});
roktElement.addEventListener("RoktPlatformEvent", (event) => {
console.log("RoktPlatformEvent received: ", event.detail);
// Send to your backend to forward to Rokt
fetch("/api/rokt-events", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(event.detail),
});
});
// Render the experience with the payload from your backend
roktElement.renderExperiences(payload);
📦 Installation Guide
The library is available as an npm package. To install it, use the following commands:
npm install @rokt/ux-helper-web@stable
For testing new features, use @latest instead of @stable:
npm install @rokt/ux-helper-web@latest
🔹 Version Tags Explained
@stable: This tag points to the latest production-ready version of the library. It is recommended for applications that require stability and reliability.@latest: This tag points to the most recent version, including new features and improvements that may not yet be fully tested. Only use this for development and testing purposes to access the latest updates before they are officially marked as stable.
CDN Usage
If you prefer to use a CDN, you can include the library directly in your HTML:
<!-- Use the latest stable version -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.cjs"></script>
<!-- Or use the latest version with newest features -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web@latest/dist/index.cjs"></script>
The package also provides different module formats:
<!-- CommonJS format (for direct browser usage) -->
<script src="https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.cjs"></script>
<!-- ESM format (for modern applications) -->
<script type="module">
import * as RoktUXHelper from 'https://cdn.jsdelivr.net/npm/@rokt/ux-helper-web/dist/index.mjs';
</script>
Register element and render the payload
To start using Rokt UX Helper in React, you need to render the rokt-layout-view custom element and pass in the experience payload via the renderExperiences method.
import { useRef, useEffect } from "react";
import { RoktLayoutViewInterface, ExperiencesResponseInterface } from "@rokt/ux-helper-web";
// Define the custom element for TypeScript
declare global {
namespace JSX {
interface IntrinsicElements {
"rokt-layout-view": React.DetailedHTMLProps<React.HTMLAttributes<RoktLayoutViewInterface>, RoktLayoutViewInterface>;
}
}
}
function RoktLayoutView() {
const roktElement = useRef<RoktLayoutViewInterface>(null);
// Get experience data from your backend
const experienceData: ExperiencesResponseInterface = /* Fetch from your server */;
// When component mounts and experienceData is available
useEffect(() => {
if (roktElement.current && experienceData) {
roktElement.current.renderExperiences(experienceData);
}
}, [experienceData]);
return (
<rokt-layout-view
ref={roktElement}
id="rokt-layout-placeholder"
></rokt-layout-view>
);
}
export default RoktLayoutView;
Note: The custom elements are automatically registered when the
@rokt/ux-helper-webpackage is imported. You don't need to explicitly callregisterCustomElements()unless you have a specific reason to do so.
Handling Events
Event Handling
Rokt UX Helper provides two types of events to help you track user interactions and communicate with the Rokt platform.
UX Events
Use UX Events to receive real-time feedback on user interactions:
roktElement.addEventListener('RoktUXEvent', (event) => {
// Use these events to tailor your user experience
console.log('RoktUXEvent received:', event.detail);
});
All UX Events
| Event | Description |
|---|---|
| OfferEngagement | Triggered when the user engages with the offer |
| PositiveEngagement | Triggered when the user positively engages with the offer |
| LayoutInteractive | Triggered when a layout is rendered and interactable |
| LayoutClosed | Triggered when a layout is closed by the user |
| LayoutCompleted | Triggered when the offer progression ends with no more offers to display |
| LayoutFailure | Triggered when a layout fails to display |
Platform Events
Platform events are essential for integration and must be sent to Rokt via your backend. These events return a full JSON payload with event data and integration details:
roktElement.addEventListener('RoktPlatformEvent', (event) => {
// Forward this payload to Rokt via your backend
fetch('/api/rokt-events', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event.detail)
});
});
Example Platform Event Payload
{
"events": [
{
"eventType": "SignalImpression",
"eventTime": "2024-12-05T04:42:54.683Z",
"sessionId": "b23d004d-b2e6-43e9-b254-d9193e650000",
"parentGuid": "9b6f0e5b-621d-4597-8a73-71d6a5b43a74",
"pageInstanceGuid": "b23d004d-b2e6-4b82-b7a2-84a13b6c57c5",
"metadata": [
{
"name": "clientTimeStamp",
"value": "2024-12-05T04:42:54.683Z"
},
{
"name": "captureMethod",
"value": "ClientProvided"
}
]
}
],
"integration": {
"name": "UX Helper Web",
"version": "1.0",
"framework": "JS",
"platform": "Web",
"layoutSchemaVersion": "1.3.0",
"deviceLocale": "en-GB",
"deviceModel": "Desktop Computer",
"deviceType": "Desktop",
"operatingSystem": "MacOS",
"operatingSystemVersion": "10.15.7",
"packageName": "UX Helper Web",
"packageVersion": "1.0"
},
"pluginId": "3333926045359669274"
}
For more details on Platform Events, refer to the API reference.
Sending Events to Layouts
You can also send events to the rendered layouts using the send method. This is useful for communicating with layouts based on actions in your application:
// Send a cart update event to all rendered layouts
await roktElement.send('V2_UPDATE_CART_ITEM', {
cartItemId: "item-123",
quantity: 2
});
This example sends a cart item update event that layouts can respond to, such as updating promotional offers based on quantities.
Handling Overlay Experiences
To support overlay experiences that target the body selector, add the render-overlay attribute:
function RoktLayoutView() {
const overlayRef = useRef<RoktLayoutViewInterface>(null);
// Same event handling and experience rendering as above
// The same `rokt-layout-view` can handle your embedded and overlay placements
return (
<rokt-layout-view
ref={overlayRef}
id="rokt-layout-placeholder"
render-overlay
></rokt-layout-view>
);
}
Complete Example
Here's a complete example of a React component that renders the Rokt UX Helper and handles both events:
import { useRef, useEffect, useState } from "react";
import {
RoktLayoutViewInterface,
ExperiencesResponseInterface,
} from "@rokt/ux-helper-web";
declare global {
namespace JSX {
interface IntrinsicElements {
"rokt-layout-view": React.DetailedHTMLProps<
React.HTMLAttributes<RoktLayoutViewInterface>,
RoktLayoutViewInterface
>;
}
}
}
function RoktLayoutView() {
const roktElement = useRef<RoktLayoutViewInterface>(null);
const [experienceData, setExperienceData] =
useState<ExperiencesResponseInterface | null>(null);
// Fetch experience data from your backend when component mounts
useEffect(() => {
const fetchExperienceData = async () => {
try {
const response = await fetch("/api/rokt-experiences");
const data = await response.json();
setExperienceData(data);
} catch (error) {
console.error("Failed to fetch experience data:", error);
}
};
fetchExperienceData();
}, []);
useEffect(() => {
const currentRoktElement = roktElement.current;
const handleRoktUXEvent = (event: Event) => {
const customEvent = event as CustomEvent;
console.log("RoktUXEvent received:", customEvent.detail);
};
const handleRoktPlatformEvent = (event: Event) => {
const customEvent = event as CustomEvent;
console.log("RoktPlatformEvent received:", customEvent.detail);
// Send to your backend to forward to Rokt
fetch("/api/rokt-events", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(customEvent.detail),
});
};
if (currentRoktElement) {
currentRoktElement.addEventListener("RoktUXEvent", handleRoktUXEvent);
currentRoktElement.addEventListener(
"RoktPlatformEvent",
handleRoktPlatformEvent
);
// Render experiences when data is available
if (experienceData) {
currentRoktElement.renderExperiences(experienceData);
}
}
return () => {
if (currentRoktElement) {
currentRoktElement.removeEventListener(
"RoktUXEvent",
handleRoktUXEvent
);
currentRoktElement.removeEventListener(
"RoktPlatformEvent",
handleRoktPlatformEvent
);
currentRoktElement.close(); // Clean up when component unmounts
}
};
}, [experienceData, roktElement]);
return (
<>
<rokt-layout-view
ref={roktElement}
id="rokt-layout-placeholder"
render-overlay
></rokt-layout-view>
</>
);
}
export default RoktLayoutView;
Summary
Integrating rokt-layout-view into your React project is straightforward and provides a flexible way to manage views and experiments. By following the steps outlined in this guide, you can add rokt-layout-view into your project and take full advantage of the powerful features offered by Rokt UX Helper.
🙋 FAQ
What is the rokt-layout-view?
The rokt-layout-view is a custom element that is used to render the Rokt Layouts on your website. It is a web component that can be added to your HTML view and used to render the experience payload.
What are the interfaces for the rokt-layout-view?
The rokt-layout-view interface is defined in the @rokt/ux-helper-web package. You can find the interface here: RoktLayoutViewInterface
export interface RoktLayoutViewInterface extends HTMLElement {
renderExperiences(data: ExperiencesResponseInterface): void;
close(): void;
send<T>(name: string, data?: T): Promise<void>;
}
How do I handle overlay experiences?
To support overlay experiences that target the body selector, add the render-overlay attribute to your rokt-layout-view element. It's recommended to place the overlay element at the end of the <body> tag to ensure proper z-index stacking and avoid potential DOM conflicts.
How do I determine if I need embedded or overlay experiences?
Embedded Experiences
Embedded experiences integrate directly within your page layout at specific points. Use these when:
- You want the experience to appear within your page flow
- You have a specific location where the content should be displayed
- You want the experience to respect surrounding content layout
<rokt-layout-view id="rokt-placement"></rokt-layout-view>
Overlay Experiences
Overlay experiences appear on top of your content, potentially covering parts of your page. Use these when:
- You want the experience to appear as a modal dialog or popup
- The content should grab the user's attention and focus
- The experience needs to be visually separated from the main page content
<rokt-layout-view id="rokt-overlay" render-overlay></rokt-layout-view>
Your Rokt Account Manager can help determine which type best suits your needs based on your business goals and design requirements.
How can I detect if the experience has rendered successfully?
You can listen for the RoktUXEvent with the LayoutInteractive event type, which is triggered when a layout is successfully rendered and ready for interaction:
roktElement.addEventListener('RoktUXEvent', (event) => {
if (event.detail.eventName === 'LayoutInteractive') {
console.log('Experience is successfully rendered and interactive');
}
});
What should I do if I need multiple placement locations?
You can add multiple rokt-layout-view elements with different IDs to target different placement locations on your page. Each element should have a unique ID that matches the target selector in your configured experiences.
How do I debug integration issues?
Check your browser console for any warnings or errors from the Rokt UX Helper. You can also use the browser's element inspector to examine the rokt-layout-view elements and their shadow DOM content. For more detailed debugging, refer to the troubleshooting guide.
Is the Web UX Helper compatible with all browsers?
The Web UX Helper is compatible with all modern browsers that support Web Components (Chrome, Firefox, Safari, Edge). For older browsers, you may need to use polyfills.
What events can I send to the rokt-layout-view?
You can send various events to communicate with the rendered layouts. A common example is the V2_UPDATE_CART_ITEM event, which allows you to inform layouts about cart changes:
await roktElement.send('V2_UPDATE_CART_ITEM', {
cartItemId: "item-123",
quantity: 2
});
This helps create dynamic experiences that react to user actions in your application. For more events, refer to the API reference.
How do I contribute to the project?
As an open source project, we welcome contributions! Visit our GitHub repository to submit issues, create pull requests, or explore the codebase.
Are there any advanced guides for the Web UX Helper?
Yes, for more advanced usage, refer to the Web UX Helper Advanced Guide.