Skip to main content

Web SDK Integration Guide

This tutorial explains how to integrate the new and enhanced Rokt SDK into a website or app for Rokt Ecommerce clients who want to capture user events and insert relevant placements (flexible iframes that can display any type of Rokt campaign) in their sites.

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.

note

These instructions require development resources to complete. If you need additional assistance, please reach out to your Rokt account manager. Shopify stores can set up a Rokt placement in seconds using the Rokt Ecommerce app — no coding needed!

note

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 entire SDK initialization script into your site.

Every site is different, but Rokt recommends including the SDK initialization script on every page of your site. This ensures that the SDK always initializes, providing 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 main index.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 will 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.

note

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");

Rokt recommends setting as many of the following user attributes as possible:

User Attribute KeyExample ValueNotes
firstnameJohnThe customer's first name.
lastnameDoeThe customer's last name.
mobile3125551515Phone numbers can be formatted either as 1112345678 or +1 (222) 345-6789.
age33The customer's age.
dob19900717Date of birth. Formatted as yyyymmdd.
genderMThe customer's gender. For example, M, Male, F, or Female.
cityBrooklynThe customer's city.
stateNYThe customer's state.
zip11201The customer's zip code.
titleMrThe customer's title. For example, Mr, Mrs, Ms.
languageenLanguage associated with the purchase.
value52.25The value of the customer.
predictedltv136.23The total predicted lifetime value of the customer.

All user attributes (including list attributes and tags) must have distinct names.

4. Track Funnel Events

The Rokt SDK allows you to implement event tracking to collect data describing your users' journeys through your site. You can then use this data to optimize your users' experience.

There are three primary event types you can track with the SDK:

  • Page View Events: These are events you can trigger when a page of your site is loaded.
  • Custom Events: These are freeform events you create to track information specific to your site.
  • Commerce Events: These are events specific to ecommerce that can describe the different stages of the shopping experience, including adding items to a cart and making a final purchase.

When first integrating with the Rokt SDK, start by implementing page view tracking. To learn about tracking custom and commerce events, see the Appendix.

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 from document.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
}
);
});

5. Show a Placement

The main value of the Rokt SDK is unlocked through the selectPlacements method, which serves a placement that is hyper-relevant to your customers based on the attributes you provide.

Once the Rokt integration has been initialized, you can call the selectPlacements method on any page or component of your site where you would like a placement to be served. You should call selectPlacements as soon as the page has loaded, the SDK has initialized, and the suggested attributes shown in the code sample below are available to be included in your call.

You can also pass in a page identifier to identifier as shown in the snippet below. This uniquely identifies the page where the Rokt placement will be added, and is useful if you have a multi-step checkout flow that uses the same URL on multiple pages. You can use any value you want for your page identifier, but some examples include:

  • stg.rokt.conf - A confirmation page in a staging (or testing) environment.
  • prod.rokt.conf - A confirmation page in a production environment.
  • stg.rokt.payments - A payments page in a staging (or testing) environment.
  • prod.rokt.payments - A payments page in production environment.

When calling selectPlacements you should provide at least the email, firstname, lastname, billingzipcode and confirmationref attributes. Additional attributes you may want to include are shown the example.

note

Both user attributes set prior to a selectPlacements call by using currentUser.setUserAttribute and attributes set in a selectPlacements call are sent to Rokt. However, if you do set a user attribute twice (prior to the selectPlacements call, and within the selectPlacements call), the newest value set in the selectPlacements call is used.

For example, if you set the user's first name using currentUser.setUserAttribute("firstname", "Johnathan") but you also include "firstname": "John" within the attributes object of selectPlacements, then the value "John" is sent to Rokt.

const selection = await window.mParticle.Rokt.selectPlacements({
identifier: "yourPageIdentifier",
attributes: {
"email": "j.smith@example.com", // Customer email address used at checkout
"firstname": "Jenny", // Customer first name
"lastname": "Smith", // Customer last name
"confirmationref": "54321", // Order / confirmation reference number
"billingzipcode": "90210", // Billing zip or postcode of customer
"amount": "100.00", // Decimal transaction amount e.g. 300.5
"paymenttype": "VISA", // E.g. Gift card | Chase, Visa
"ccbin": "372888", // Credit card bin e.g. 372888
"mobile": "123-456-7890", // Customer mobile / cell number
"country": "USA", // ISO Alpha-2 Country Code
"language": "en", // ISO 639-1 2 letter lanugage code
"currency": "USD", // Transaction currency e.g. USD
"billingaddress1": "", // Customer address line 1
"billingaddress2": "", // Customer address line 2
"age": "29", // Customer age
"gender": "f", // Customer gender m / f
"cartItems": JSON.stringify(["item 1", "item 2", "item 3"]), // Stringified cart contents

// You can also pass extra attributes relevant to the transaction here
// See link below for a full list of attributes
"shippingtype": "Priority Express"
}
});

Close a placement

If your site is a single page application, once you have served a placement by calling selectPlacements, it's important that you close the placement after the user has navigated to a different page. This prevents the placement from still being displayed to the user when they navigate back.

To close and remove a placement, call .close() on the placement object you created:

// Closes the placement called 'selection'
selection.close();
note

For a full list of supported attributes, see Data Attributes.

Your dedicated Rokt team will configure your placement layouts for you so they match your brand and UX styleguide.

6. Test Your Integration

Rokt recommends testing your new integration to ensure the SDK initializes correctly, and that events are logged successfully.

  1. Open a new browser window.
  2. Open your browser's developer tools panel. For most browsers, you can do this by right-clicking on your screen and clicking Inspect.
  3. From the developer tools panel, go to the Network tab and type experiences into the filter bar.
  4. 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.
  5. 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.
  6. 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.

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:

  1. Go to your browser's developer tools panel and select the Console tab.

  2. 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.

    Web SDK integration testing

  3. 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'
}
);

Track Commerce Events

Tracking a commerce event requires three steps:

  1. Defining the product or products that are being purchased within a variable using the createProduct method.
  2. Creating an object to contain a transaction summary.
  3. Calling the logProductAction method, including your product definitions in an array and transaction summary.
1. Define the product

When defining the product, create a new product using the mParticle.eCommerce.createProduct method, passing in the following attributes and an optional JSON object containing custom product attributes that you can define as key/value pairs.

note

Product attributes must be added in the order shown below. If you do not have a value for any of the optional attributes, you must set the value to null. You cannot skip or omit any attributes with the exception of the optional JSON object for custom attributes.

Prduct AttributeDescriptionData TypeRequired
NameThe name of the product being purchased.StringYes
SKUThe stock keeping unit for the product.StringYes
PriceThe price of the product.DecimalYes
QuantityThe number of units.IntegerNo
VariantThe specific product version, if you offer variants. For example: size or color.StringNo
CategoryThe category that the product belongs to.StringNo
BrandThe brand name for the product.StringNo
PositionThe position.StringNo
Coupon codeThe coupon code for the product.StringNo
var product1 = mParticle.eCommerce.createProduct(
'Double Room - Econ Rate', // Name (required)
'econ-1', // SKU (required)
100.00, // Price (required)
4, // Quantity
'variant', // Variant
'room', // Category
'lodge-o-rama', // Brand
'banner', // Position
null, // Coupon code
// Add any optional custom attributes in an object of key/value pairs
{
'ocean-view': true,
'balcony': false
}
);
2. Summarize the transaction

Create a summary of the transaction within an object called transactionAttributes.

var transactionAttributes = {
Id: 'foo-transaction-id',
Revenue: 430.00,
Tax: 30
};
3. Log the commerce event

To log the commerce event, call mParticle.eCommerce.logProductAction, and set ProductActionType to one of the supported action types listed below.

Include your product definitions in an array. If you only have a single product definition, still include it in an array as shown in the example.

You can also set custom event attributes for the commerce event in customAttributes.

// Several types of "product actions" are supported, such as AddToCart and Checkout. This example uses the Purchase product action.
mParticle.eCommerce.logProductAction(
// The type of product action being logged. In this example, the type is "Purchase"
mParticle.ProductActionType.Purchase,
// The array containing the product definitions you already created in Step 1.
[product1],
// Custom attributes describing the commerce event
customAttributes = {
'sale': true
},
// This space is for specifying custom flags for mParticle by Rokt integrations. Rokt Ecommerce customers can ignore this section by entering 'null'.
null,
// The transactionAttributes object you already created in Step 2.
transactionAttributes
);

When calling the logProductAction method, you must specify the product action type.

Supported production action types
  • AddToCart
  • RemoveFromCart
  • Checkout
  • CheckoutOption
  • Click
  • ViewDetail
  • Purchase
  • Refund
  • AddToWishlist
  • RemoveFromWishlist
  • Unknown

Passing Additional Integration Launcher Options

The Rokt SDK can accept additonal optional parameters to configure the behavior of the integration.

// Include this as part of the initialization script in step 1 above
windiow.mParticle.config.launcherOptions = {
noFunctional: true,
// see all proprties that can be passed below
};
Properties
noFunctional (optional)

noFunctional? : boolean

default false

A boolean flag allowing management of user preference for functional cookies. Functional cookies allow you to provide the most relevant and optimal customer experiences on your own site, with enhanced personalization. They also help power advanced functionality within the checkout (e.g. selling Upsells). In practice, setting the value to true prevents Rokt from using any 1st party tracking IDs. Details on the functionality and the impact of using this option.


pageInitTimestamp (optional)

pageInitTimestamp? : Date

In the event that the Integration Launcher is initialized on a virtual page of a SPA, this value allows you to provide the timestamp of the page being initialized. This allows Rokt to correctly measure the load performance relative to the page that triggered it without external factors such as how long it took user to reach that page. With this information, Rokt can detect any anomaly in the load times that could impact the efficiency of the integration.

default PerformanceNavigationTiming.responseStart

See Anomaly detection for how Rokt tracks load performance.

See Single page applications on details of SPA integrations


sessionId (optional)

sessionId? : string

Rokt session ID to be passed in case you have already generated your session ID.

For example, it is possible to have your session ID generated by connecting with the Rokt backend before visiting a page where your tag is displayed. In this case, you should provide the previously generated Rokt session ID as this parameter so Rokt can pair both interactions together.


overrideLinkNavigation? : boolean

default false

When set to true, Rokt will no longer handle link openings directly. Instead, a LINK_NAVIGATION_REQUEST partner event will be emitted.

This flag is useful in scenarios where partners require customized link handling. A common use case is managing different link behaviors—such as opening the links within a WebView while using an external browser for links from Rokt and advertisers. To distinguish between Rokt and advertiser links, partners can check if the URL contains the substring "rokt.com".

To ensure proper event handling, a timeout mechanism is in place. If a LINK_NAVIGATION_REQUEST event is not consumed within 3 seconds, an error will be raised. This precaution ensures that active subscriptions exist on the partner’s side for processing the event and if that is not the case then Rokt will be notified.

Was this article helpful?