Web SDK Integration Guide
This tutorial explains how to integrate the new and enhanced Rokt Web SDK into a website for advertisers who want to collect data about conversions, user attributes, and user behavior to improve ad relevance.
Your dedicated account representative will help configure your account for the Web SDK. They will provide you with both the API key required to initialize the SDK and additional resources needed to render the most relevant experiences for your customers.
The below instructions will require development resources to complete. If you require additional assistance, please reach out to your Rokt account manager.
Work with your Rokt account manager to first implement the SDK in a development environment. This allows you to thoroughly test and troubleshoot your integration before releasing it in a production environment.
First-Party Domain Configuration
Rokt recommends using a first-party domain when integrating the SDK into your site. This ensures that the Rokt SDK uses your own domain when making calls to Rokt's API, providing your customers with a seamless experience and minimizing the risk of blocked content.
To learn how to configure a first-party domain for your SDK integration, see First Party Domain Integration.
1. Initialize the Rokt SDK
To initialize the SDK, copy and paste the SDK initialization script into your site.
Every site is different, but Rokt recommends including the SDK script on every page. This ensures the lowest offer delivery latency and the highest user identification accuracy.
- Single-page Applications (SPA): If your website is an SPA, insert the initialization script into the
<head>
of the mainindex.html
page, or the primary location where the rest of your content is rendered. - Multi-page Applications (MPA): If your website is an MPA and you use a template-base rendering system (most common), place the initialization script in the primary shared layout file. If you don’t use a template-based rendering system, place the script in each HTML file of your website.
Note that although each page may include the script, due to browser caching, the SDK would load from cache by default rather than being loaded upon each page load of your website.
SDK Initialization Script
<script type="text/javascript">
// Enter your Rokt API key
const API_KEY = "YOUR_API_KEY";
// Enter your custom subdomain if you are using a first-party domain configuration (optional)
const ROKT_DOMAIN = "https://apps.rokt-api.com";
window.mParticle = {
config: {
// Set the data environment:
// Set isDevelopmentMode to true if you are still testing your integration.
// Set isDevelopmentMode to false if your integration is ready for production data.
isDevelopmentMode: true,
// Identify the current user:
// If you do not have the user's email address, you can pass in a null value
// identifyRequest: {
userIdentities: {
// If you're using an un-hashed email address, set it in 'email'.
email: 'j.smith@example.com',
// If you're using a hashed email address, set it in 'other' instead of `email`.
other: 'sha256 hashed email goes here'
}
},
// If the user is identified with their email address, set additional user attributes.
identityCallback: function(result) {
if (result.getUser()) {
result.getUser().setUserAttribute('attribute-key', 'attribute-value');
}
}
};
// Load the SDK
(function(e) { window.mParticle = window.mParticle || {}; window.mParticle.EventType = { Unknown: 0, Navigation: 1, Location: 2, Search: 3, Transaction: 4, UserContent: 5, UserPreference: 6, Social: 7, Other: 8, Media: 9 }; window.mParticle.eCommerce = { Cart: {} }; window.mParticle.Identity = {}; window.mParticle.Rokt = {}; window.mParticle.config = window.mParticle.config || {}; window.mParticle.config.rq = []; window.mParticle.config.snippetVersion = 2.6; window.mParticle.ready = function(e) { window.mParticle.config.rq.push(e); }; ["endSession", "logError", "logBaseEvent", "logEvent", "logForm", "logLink", "logPageView", "setSessionAttribute", "setAppName", "setAppVersion", "setOptOut", "setPosition", "startNewSession", "startTrackingLocation", "stopTrackingLocation"].forEach(function(e) { window.mParticle[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift(e); window.mParticle.config.rq.push(t); }; }); ["setCurrencyCode", "logCheckout"].forEach(function(e) { window.mParticle.eCommerce[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("eCommerce." + e); window.mParticle.config.rq.push(t); }; }); ["identify", "login", "logout", "modify"].forEach(function(e) { window.mParticle.Identity[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Identity." + e); window.mParticle.config.rq.push(t); }; }); ["selectPlacements","hashAttributes","setExtensionData"].forEach(function(e) { window.mParticle.Rokt[e] = function() { var t = Array.prototype.slice.call(arguments); t.unshift("Rokt." + e); window.mParticle.config.rq.push(t); }; }); var t = window.mParticle.config.isDevelopmentMode ? 1 : 0, n = "?env=" + t, a = window.mParticle.config.dataPlan; if (a) { var o = a.planId, r = a.planVersion; o && (r && (r < 1 || r > 1e3) && (r = null), n += "&plan_id=" + o + (r ? "&plan_version=" + r : "")); } var i = window.mParticle.config.versions, s = []; i && Object.keys(i).forEach(function(e) { s.push(e + "=" + i[e]); }); var c = document.createElement("script"); c.type = "text/javascript"; c.async = !0; window.ROKT_DOMAIN = ROKT_DOMAIN || 'https://apps.rokt-api.com'; mParticle.config.domain = ROKT_DOMAIN.split('//')[1]; c.src = ROKT_DOMAIN + "/js/v2/" + e + "/app.js" + n + "&" + s.join("&"); var l = document.getElementsByTagName("script")[0]; l.parentNode.insertBefore(c, l); })(API_KEY);
</script>
When inserting the initialization script into your site, configure the following settings:
1.1 Enter your Rokt API Key
Set API_KEY
to the Rokt API key provided by your dedicated Rokt account manager.
Your Rokt API Key is a unique credential provided by your Rokt account representative that securely enables your site to connect and interact with the Rokt SDK.
1.2 Enter your custom subdomain (optional)
If you want to route the SDK through your own domain, follow the instructions in First-Party Domain Configuration, and set ROKT_DOMAIN
to the subdomain you created.
A custom subdomain allows the Rokt SDK to be routed through your own domain, reducing the risk of ads or data being blocked by browsers or ad blockers.
This step is optional. You can leave ROKT_DOMAIN
set to https://apps.rokt-api.com
, but requests to the Rokt SDK will be routed through apps.rokt-api.com
.
1.3 Configure your data environment
Rokt maintains two data environments: Development for labeling and storing data for testing purposes and Production for collecting actual customer activity.
If you are still testing the Rokt SDK, set isDevelopmentMode
to true
.
If you are done testing and want to begin collecting live customer activity, set isDevelopmentMode
to false
.
1.4 Identify the user
When the SDK is initialized, it can identify the current user so that any collected data is correctly attributed to them and to ensure they are shown the most relevant ads based on their behavior.
The SDK initialization script includes an object called identifyRequest
:
identifyRequest: {
userIdentities: {
// Set the user's raw email addres in 'email'
email: 'j.smith@example.com',
// Set the user's hashed email address in 'other'
other: 'sha256 hashed email goes here'
}
}
Within identifyRequest
, pass the user’s email address into the email
field if it is un-hashed or other
if it is hashed using SHA256.
Always include identifyRequest
in the initialization script, even if you don’t have the user’s email address at the time of initialization.
If you don’t have the user’s email address, pass in a null value. The SDK will still initialize, and you can identify the user later by following the instructions in 2. Identify the User.
1.5 Set additional user attributes
The initialization script includes a callback function that allows you to set additional user attributes for the user if they are successfully identified with their email address:
// The identityCallback determines if the identifyRequest was successful.
identityCallback: function(result) {
if (result.getUser()) {
// If the user was identified, set additional user attributes with setUserAttribute.
result.getUser().setUserAttribute('attribute-key', 'attribute-value');
}
}
For a list of attributes Rokt recommends collecting for your users, see Recommended user attributes.
2. Identify the User
During initialization, the SDK submits an identifyRequest to Rokt with the user’s email address to identify the current user.
In addition to identifying the user on initialization, whenever the user provides their email address after the SDK has initialized (for example, when they log in or make a purchase), you should call the identify method to pass their email to Rokt. This ensures that data is correctly attributed to the current user.
To identify the user, first create an identifyRequest
object to contain the user’s email address.
If you are providing an un-hashed email address, use:
const identifyRequest = {
userIdentities: {
email: 'j.smith@example.com'
}
};
If you are providing a hashed email address, use:
const identifyRequest = {
userIdentities: {
other: 'sha256 hashed email goes here'
}
};
Next, you have the option of setting additional user attributes when identifying a user by creating a callback function. If the identifyRequest
succeeds, then the user attributes you set with setUserAttribute
are assigned to the user.
const identityCallback = function(result) {
if (result.getUser()) {
result.getUser().setUserAttribute('attribute-key', 'attribute-value');
}
};
For a list of attributes Rokt recommends collecting for your users, see Recommended user attributes.
Finally, after creating your identifyRequest
and your identityCallback
, to set any additional attributes, call the identify method, passing in the identifyRequest
and identityCallback
objects you just created:
mParticle.Identity.identify(identifyRequest, identityCallback);
For example, to identify a user named Jane Smith with the email address j.smith@example.com
(and you don't need to hash their email address) you would use:
const identifyRequest = {
userIdentities: {
email: 'j.smith@example.com'
}
};
const identityCallback = function(result) {
if (result.getUser()) {
result.getUser().setUserAttribute('firstname', 'Jane');
result.getUser().setUserAttribute('lastname', 'Smith');
}
};
mParticle.Identity.identify(identifyRequest, identityCallback);
3. Set User Attributes
The examples above show how to set user attributes when the user is identified during SDK initialization and when the user is identified after providing their email address.
However, after the user has been identified, you can set user attributes at any time. These attributes are included with your ad placements or logged events. You can also set user attributes directly when inserting a placement.
To set user attributes, run the following:
// To retrieve the current user, call getCurrentUser.
const currentUser = mParticle.Identity.getCurrentUser();
// Once you have successfully set the current user to a const called `currentUser`, you can set user attributes with:
currentUser.setUserAttribute("user-attribute-key", "user-attribute-value");
// To set a list attribute, set the value of the attribute to an array of strings. For example:
currentUser.setUserAttribute("favorite-genres", ["documentary", "comedy", "romance", "drama"]);
// To remove a user attribute, call removeUserAttribute and pass in the attribute name. All user attributes share the same key space.
currentUser.removeUserAttribute("attribute-to-remove");
Recommended user attributes
Rokt recommends setting as many of the following user attributes as possible:
User Attribute Key | Example Value | Notes |
---|---|---|
firstname | John | The customer's first name. |
lastname | Doe | The customer's last name. |
mobile | 3125551515 | Phone numbers can be formatted either as 1112345678 or +1 (222) 345-6789 . |
age | 33 | The customer's age. |
dob | 19900717 | Date of birth. Formatted as yyyymmdd . |
gender | M | The customer's gender. For example, M , Male , F , or Female . |
city | Brooklyn | The customer's city. |
state | NY | The customer's state. |
zip | 11201 | The customer's zip code. |
title | Mr | The customer's title. For example, Mr , Mrs , Ms . |
language | en | Language associated with the purchase. |
value | 52.25 | The value of the customer. |
predictedltv | 136.23 | The total predicted lifetime value of the customer. |
All user attributes (including list attributes and tags) must have distinct names.
4. Track Page Views
One of the most basic event types you can track is the page view.
To log a page view, use the logPageView() method after the SDK has been initialized.
In the example below, the event includes:
- A
screen_name
derived from the last segment of the URL path (with a fallback to "home"). - The full
url
of the current page. - The
referring-page
, captured fromdocument.referrer
.
This is useful for tracking user navigation across your site without needing to manually specify page identifiers.
// Wait for the SDK to be fully loaded before logging the event
window.mParticle.ready(function() {
mParticle.logPageView(
// Event name: "page view" identifies the type of event being logged
"page view",
{
// Capture the last segment of the URL path as the screen name,
// e.g., "/products/shoes" → "shoes". Defaults to "home" if the path is empty.
"screen_name": location.pathname.split("/").filter(Boolean).pop() || "home",
// Record the full URL of the current page (including protocol, path, query, and hash)
"url": window.location.toString(),
// Capture the URL of the page that referred the user to this one,
// if available. This helps track user navigation between pages or sites.
"referring-page": document.referrer
}
);
});
The web SDK’s logPageView
method takes two arguments:
- Page Name: a string for the name of the page being loaded
- Custom Attributes: an object of key/value pairs containing information about the page
The page name field should be set to a generic page name. For example, an ecommerce website could have hundreds of product detail pages. To log these correctly, you should use a generic name (e.g. "Product Detail Page") and then log the url and other attributes of the page as attributes.
5. Track Conversions
To track a conversion, run the following code snippet on the most appropriate page that's loaded after a customer converts, such as a purchase confirmation or "thank you" page.
When pasting the code snippet into your site, make sure to:
- Replace the sample user attributes in the
.setUserAttribute
calls the actual values for your user or customer. Rokt recommends setting at least the following user attributes:firstname
lastname
zipcode
mobile
- Replace the sample conversion event attributes with with actual values from your conversion event.
When logging a conversion event, you should include as many user attributes and event attributes as possible to improve Rokt's ability to optimize your campaigns.
When you initialize the Rokt SDK, it automatically captures the Rokt Click ID and Time on Site. These are included when you log a conversion event.
// Set user attributes before logging the conversion event
currentUser.setUserAttribute("firstname", "John");
currentUser.setUserAttribute("lastname", "Doe");
currentUser.setUserAttribute("zipcode", "98103");
currentUser.setUserAttribute("mobile", "3125551515");
// Log the conversion event
mParticle.logEvent(
"conversion", // The name of the event
mParticle.EventType.Transaction, // The event type
{
"conversiontype": "signup", // Type of conversion
"confirmationref": "54321", // Transaction ID / Order ID
"amount": "", // Transaction amount e.g. 300.5
"currency": "", // Transaction currency e.g. USD
// You can track your own custom event attributes!
"CUSTOM_EVENT_ATTRIBUTE_NAME" : "CUSTOM_EVENT_ATTRIBUTE_VALUE"
}
);
6. Test Your Integration
Rokt recommends testing your new integration to ensure the SDK initializes correctly, and that events are logged successfully.
- Open a new browser window.
- Open your browser's developer tools panel. For most browsers, you can do this by right-clicking on your screen and clicking Inspect.
- From the developer tools panel, go to the Network tab and type
experiences
into the filter bar. - Navigate to the site and page where you integrated the SDK.
- Note: Make sure you open the developer tools panel before navigating to your site to ensure the
/experiences
call is recorded by the browser.
- Note: Make sure you open the developer tools panel before navigating to your site to ensure the
- In the Network tab of the developer tools panel, you should see at least one
/experiences
request. This indicates that the Web SDK loaded successfully. - Click the
/experiences
request (it should have a status of 200). Check the Payload/Request tab to verify the data being shared with Rokt.- Note: During testing, you might see another
/experiences
call with a 204 status. Make sure you are performing the check on the call with a 200 status.
- Note: During testing, you might see another
Troubleshooting
The Rokt Web SDK provides contextual error reporting. If you are having trouble validating your integration, the best way to debug the issue is by using the Console tab in your browser's developer tools panel.
While you may be encountering errors unrelated to the Rokt SDK, some common Rokt SDK errors to check for are:
Syntax errors
Make sure you are not missing any commas in your integration code.
To check for syntax errors:
-
Go to your browser's developer tools panel and select the Console tab.
-
If the file where you placed the Web SDK has an error, it should be logged in the console. Click the file to see the code and reported error.
-
Any error is indicated in the file. In particular, check that all attributes are separated by commas as shown below.
Incorrect:
email: ''
emailsha256: '',
Correct:
email: '',
emailsha256: '',
Initialization errors
- Make sure the SDK initialization script has been placed on the correct page.
- If you integrated using a tag manager, make sure you configured your tag triggers so that initialization loads on the right pages, and that your selectPlacements and conversion logging tags are firing after the SDK has initialized.
Appendix
After implementing placements and page view tracking by following the instructions above, you may want to implement additional event tracking.
Track Custom Events
You can define and track custom events by calling logEvent
and passing in the event name, the event type, and a JSON object containing a list of any custom attributes for the event.
The supported custom event types are:
Navigation
Location
Search
Transaction
UserContent
UserPreference
Social
Other
The event type is optional; if you omit event type, the event is simply categorized as unknown
.
mParticle.logEvent(
// The event name
'event-name',
// The event type
mParticle.EventType.Other,
// Include custom event attributes to further describe the event
{
'custom-attribute-name': 'custom-attribute-value'
}
);
In addition to tracking custom events and conversion events, following are some examples of commerce events you may want to track. Speak with your account manager for help identifying the best events to track, and how to implement them in your site:
purchase
- when a user makes a purchase or transaction.sign_up
- when a user signs up or registers for an event or service.first_time_deposit
- when a user provides a deposit.subscription_started
- when a user starts a subscription.app_install
- when a user installs an app.add_payment_info
- when a user adds payment details.add_to_cart
- when a user adds an item to their cart.add_to_wishlist
- when a user adds an item to their wishlist.