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.
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!
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 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 will load from cache by default rather than being loaded upon each page load of your website.
SDK Initialization Script
- Replace
"YOUR_API_KEY"
with the API key provided by your dedicated Rokt team. - Set
DOMAIN
to the subdomain you created during your first-party domain configuration. This is optional: if you leave the default DOMAIN setting, requests will be routed throughapps.rokt-api.com
.
<script type="text/javascript">
// Enter your Rokt API key
const API_KEY = "YOUR_API_KEY";
// If you configured a first-party domain, set it as the value of DOMAIN instead of the default apps.rokt-api domain
const DOMAIN = "https://apps.rokt-api.com";
// Set your SDK configuration settings
window.mParticle = {
config: {
// Specify the data environment with isDevelopmentMode:
// 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 have the user's email address, include it in an object called `userIdentities` within `identifyRequest` as shown below.
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'
},
}
},
};
// 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.5; 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.DOMAIN = window.DOMAIN || 'https://apps.rokt-api.com'; c.src = DOMAIN + "/js/v2/" + e + "/app.js" + n + "&" + s.join("&"); var l = document.getElementsByTagName("script")[0]; l.parentNode.insertBefore(c, l); })(API_KEY);
</script>
The initialization script includes the following configuration settings:
isDevelopmentMode
In the example above, isDevelopmentMode
is set to true
. This allows you to test your SDK integration by collecting "development" data. When you are ready to go live with your integration, set isDevelopmentMode
to false
to collect and send production data to Rokt.
identifyRequest
The SDK allows you to identify the current user by including their email address at the time the SDK is initalized. Rokt recommends using your customer's raw (unhashed) email address for the identifier.
2. Identify the User
During initialization, the SDK submits an identifyRequest
to Rokt using either the user's raw or hashed email address (whichever you can provide) to identify the current user.
If you can't provide the user's email address when the SDK is initialized, you should identify the user as soon as they provide their email address by calling the identify
method.
If you are providing an un-hashed email address, use:
const identifyRequest = {
userIdentities: {
email: 'j.smith@example.com'
}
};
mParticle.Identity.identify(identifyRequest);
If you are providing a hashed email address, use:
const identifyRequest = {
userIdentities: {
other: 'sha256 hashed email goes here'
}
};
mParticle.Identity.identify(identifyRequest);
3. Set User Attributes
If you have identified the current user, you can set descriptive user attributes that will be included with any ad placements or logged events. You can also set user attributes directly when inserting a placement.
To set user attributes, run the following after the SDK has initilaized and you have identified the user:
// To retrieve the current user, call getCurrentUser. This will only succeed if you have identified the user during SDK initialization or by calling the identify method.
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-name", "user-attribute-value");
// Note: all user attributes (including list attributes and tags) must have distinct names.
// Rokt recommends setting as many of the following user attributes as possible:
currentUser.setUserAttribute("firstname", "John");
currentUser.setUserAttribute("lastname", "Doe");
// Phone numbers can be formatted either as '1234567890', or '+1 (234) 567-8901'
currentUser.setUserAttribute("mobile", "3125551515");
currentUser.setUserAttribute("age", "33");
currentUser.setUserAttribute("gender", "M");
currentUser.setUserAttribute("city", "Brooklyn");
currentUser.setUserAttribute("state", "NY");
currentUser.setUserAttribute("zip", "123456");
currentUser.setUserAttribute("dob", "yyyymmdd");
currentUser.setUserAttribute("title", "Mr");
currentUser.setUserAttribute("language", "en");
currentUser.setUserAttribute("value", "52.25");
currentUser.setUserAttribute("predictedltv", "136.23");
// 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");
4. Track Funnel Events
The Rokt SDK allows you 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, call the mparticle.logPageView
method as soon as your page loads, passing in the name of the page as a string.
The name you pass in should be one of a limited set of pages, like 'homepage'
or 'product detail page'
.
The event attribute page
stores the URL of the page being loaded by a call to window.location.toString()
.
mParticle.logPageView(
// Name of the page being loaded. This should be a part of a known/limited set of pages in your site.
'page view',
// Include free-form key/values to describe the page
{
page: window.location.toString(),
'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 avaialble 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.
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"
}
});
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.
- 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'
}
);
Track Commerce Events
Tracking a commerce event requires three steps:
- Defining the product or products that are being purchased within a variable using the
createProduct
method. - Creating an object to contain a transaction summary.
- 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.
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 Attribute | Description | Data Type | Required |
---|---|---|---|
Name | The name of the product being purchased. | String | Yes |
SKU | The stock keeping unit for the product. | String | Yes |
Price | The price of the product. | Decimal | Yes |
Quantity | The number of units. | Integer | No |
Variant | The specific product version, if you offer variants. For example: size or color. | String | No |
Category | The category that the product belongs to. | String | No |
Brand | The brand name for the product. | String | No |
Position | The position. | String | No |
Coupon code | The coupon code for the product. | String | No |
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