Skip to main content

Setting up JavaScript pixels and events

How to set up a base pixel and custom events.

Updated over a week ago

How to set up pixels & events

This article will describe in detail how to set up a base pixel and events, powering consideration campaigns, conversion campaigns, audience building, and attribution tracking.

In this article, you'll learn how to:

To learn more about our Events API, read this article.

To learn more connecting Shopify events, read this article.


Step 1: Find your base pixel

When creating your campaign, we recommend setting up your base pixel at the start.

Note: Events can't fire on your website without a base pixel, so it's important that you place the base pixel before setting up additional events

First, head to the Events page in the top nav:

Then, click "Set up events with Roku":

Note: Some advertisers may use partners like Shopify or Google Tag Manager, which can streamline event tracking setup. In this case, choose "Connect with a partner".

Next, select "JavaScript pixel" and click "Continue":

Next, copy the base pixel code. This is just an example.

To improve event match rates on Roku, we recommend enabling first-party cookies and automatic advanced matching:


Step 2: Place your base pixel

Note: When you place a base pixel, a page view event is automatically included for you. You will not need to install a separate page view event.

Copy the code that's generated for your product and send it to your web developer, or if you're placing it yourself, locate your website's header code. If your site has a global header, you only need to place the code once. If not, place it in the header code on every webpage, like this:

<html>
<head>
<!-- Roku Pixel Code -->
<script>
!function(e,r){if(!e.rkp){var t=e.rkp=function(){
var e=Array.prototype.slice.call(arguments)
;e.push(Date.now()),t.eventProcessor?t.eventProcessor.apply(t,e):t.queue.push(e)
};t.initiatorVersion="1.0",t.queue=[],t.load=function(e){
var t=r.createElement("script");t.async=!0,t.src=e
;var n=r.getElementsByTagName("script")[0]
;(n?n.parentNode:r.body).insertBefore(t,n)},rkp.load("https://cdn.ravm.tv/ust/dist/rkp.loader.js")}
}(window,document);
rkp("init","<your id goes here>"),rkp('event', 'PAGE_VIEW');;
</script>
<!-- End Roku Pixel Code -->
</head>
<body>
</body>
</html>

Step 3: Select your events

Next, choose from a list of 24 standard events:

You can also add events from the event group details page after you’ve added your first event.

Note: We recommend adding as many events as possible. Each new event you install unlocks the ability to optimize your campaigns for those specific actions and build audiences based on that behavior.


Step 4: Placing your events

After you select your events, you'll get a unique code snippet for each event, which again, you can send to your web developer or follow the steps to place it yourself.

Example 1: Complete implementation with base pixel and events

This example shows the base pixel in the header with the automatic page view event, plus a simple "Add to Cart" event on a button click:

<!DOCTYPE html>
<html>
<head>
<!-- Base Roku Pixel Code (must be placed first) -->
<!-- Roku Pixel Code -->
<script>
!function(e,r){if(!e.rkp){var t=e.rkp=function(){
var e=Array.prototype.slice.call(arguments)
;e.push(Date.now()),t.eventProcessor?t.eventProcessor.apply(t,e):t.queue.push(e)
};t.initiatorVersion="1.0",t.queue=[],t.load=function(e){
var t=r.createElement("script");t.async=!0,t.src=e
;var n=r.getElementsByTagName("script")[0]
;(n?n.parentNode:r.body).insertBefore(t,n)},rkp.load("https://cdn.ravm.tv/ust/dist/rkp.loader.js")}
}(window,document);
rkp("init","<your id goes here>"),rkp('event', 'PAGE_VIEW');;
</script>
<!-- End Roku Pixel Code -->

<title>Product Page - Wireless Headphones</title>
<!-- Other head elements -->
</head>
<body>
<h1>Wireless Headphones</h1>
<p>High-quality wireless headphones with noise cancellation.</p>
<p>Price: $99.99</p>

<button id="addToCartButton">Add to Cart</button>

<!-- Event tracking code -->
<script>
// Wait for the DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function() {
// Get the button element
var addToCartButton = document.getElementById('addToCartButton');

// Add click event listener to the button
addToCartButton.addEventListener('click', function() {
// Fire the Add to Cart event when the button is clicked
rkp('event', 'ADD_TO_CART');

// Continue with your regular cart functionality
console.log('Product added to cart');
});
});
</script>
</body>
</html>

Example 2: Tracking a Sign-up event on form submission

<form id="signupForm">
<input type="email" id="email" placeholder="Your email" required>
<button type="submit">Sign Up</button>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
var form = document.getElementById('signupForm');

form.addEventListener('submit', function(event) {
// Prevent the default form submission
event.preventDefault();

// Fire the Sign-up event
rkp('event', 'SIGN_UP');

// Continue with your form submission
console.log('Form submitted, tracking event sent');
form.submit();
});
});
</script>

Example 3: Purchase event on an order confirmation page

Place this code on your order confirmation page to track completed purchases:

<script>
// This code should be placed in the body of your order confirmation page
document.addEventListener('DOMContentLoaded', function() {
// Fire the Purchase event when the confirmation page loads
rkp('event', 'PURCHASE');
});
</script>

Note: For optimal performance, place event tracking code as close as possible to where the action occurs:

  • For button clicks and form submissions, attach the event to the relevant user interaction.

  • For page-level events like purchases on confirmation pages, you can place the code in the head or at the beginning of the body.


Step 5 (optional): Augment your events

You can augment your event data with additional metadata to unlock more advanced reporting capabilities—such as tracking Return on Ad Spend (ROAS) and order value. These metadata fields also support powerful use cases like deduplicating events across the JS Pixel and Events API, manually passing identifiers like phone numbers and email addresses, applying custom privacy settings, and more.

Basic Event Customization Examples:

// Override the event ID and add order information
rkp('event', 'PURCHASE', {
event_id: "custom-event-123", // Custom event ID instead of auto-generated one
order_id: "ORD-98765",
value: 39.99,
currency: "USD"
});

// Add source URL and referrer information
rkp('event', 'PAGE_VIEW', {
event_source_URL: "https://www.example.com/product-page",
referrer_URL: "https://www.google.com"
});

// Set opt-out and data processing flags
rkp('event', 'SIGN_UP', {
opt_out: false,
dpo_flag: true,
data_processing_country: true,
data_processing_state: true
});

Advanced Event Customization Examples:

// Comprehensive purchase event with user data
rkp('event', 'PURCHASE', {
// Event core attributes
event_id: "purchase-1234567",
event_source: "website",

// Custom data attributes
value: 129.99,
currency: "USD",
order_id: "ORD-98765",
delivery_category: "HOME_DELIVERY",
num_items: 2,
content_category: "electronics",
content_ids: ["SKU-12345", "SKU-67890"],
content_name: "Wireless Headphones",
content_type: "product",

// Contents details
contents: [
{
id: "SKU-12345",
quantity: 1,
item_price: 99.99,
delivery_category: "HOME_DELIVERY"
},
{
id: "SKU-67890",
quantity: 1,
item_price: 30.00,
delivery_category: "HOME_DELIVERY"
}
],

// User data
user_data: {
is_hashed: true,
em: "f660ab912ec121d1b1e928a0bb4bc61b15f5ad44d5efdc4e1c92a25e99b8e44a", // Hashed email
ph: "74c8c5f708fd8c946c8b4f8a95743507e1930bae82eef53f7a7c96c6288c7086", // Hashed phone
external_id: "user-987654",
client_ip_address: "192.168.1.1",
client_user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
subscription_id: "sub-12345",
us_privacy: "1YNN"
},
});

Event with Geographic User Data:

rkp('event', 'SIGN_UP', {
event_id: "signup-7654321",

// Custom data
status: "COMPLETED",

// User geographic data
user_data: {
is_hashed: true,
ct: "4ed9407630eb1c60b4b5eb1b2e9cc1576a61c84fa2425c2670144af5a2e641d4", // Hashed city
st: "ca3e27457f29a4178594a8017c8c9c79a6f27f7e1a884dbcad8871a7a58c2ba0", // Hashed state
zp: "c42a54b9641d4a6fd6edd8a3d7c983d348d2a9730e8c2a0e813d5a1c0e3b6f87", // Hashed zip
country: "US",
external_id: "user-123456"
}
});

Add to Cart Event with Analytics IDs:

rkp('event', 'ADD_TO_CART', {
value: 49.99,
currency: "USD",
content_ids: ["SKU-34567"],
content_name: "Wireless Mouse",

// Analytics integration
user_data: {
ga_session_id: "1234567890",
ga_client_id: "555666777.1234567890",
ga_gclid: "Cj0KCQiA1sucBhDgARIsAFoU1y-xN7_FOQCfkwKj",
ga_measurement_ids: ["G-XXXXXXXXXX", "UA-XXXXXXXXX-1"]
}
});

Standard Event Parameters:

Any of the following additional properties can be appended to your metadata.

Note: To report on ROAS, average order value, and total order value, you will need to send the "value" parameter.

Event Parameter

Data type

Description

event_name

String

Name of the event (required)

event_source

String

Source of the event (required)

event_id

String

The unique string generated by the site. Used for deduplication: If you install the Roku Pixel (client-side) on your website and are sending events using the Events API (server side), then make sure to pass this field from both client and server side to eliminate duplicate fires from client-side and server-side.

Deduplication will only work if the two events are fired within 10 minutes of each other with the same event ID

event_source_URL

String

URL where the event occurred

referrer_URL

String

Referring URL that led to the event

opt_out

Boolean

Flag indicating if the user has opted out of tracking

Limited Data Use (LDU) is a data processing option that lets you limit how your event data is used in Roku's systems and helps to better support your compliance efforts with various US state privacy laws.

A value of "true" triggers the LDU flag. See the LDU article for more detailed implementation instructions.

partner_name

String

Name of the partner

status

String

Status of the event

Example: Generating and Using an Event ID

Here's a complete example showing how to generate a consistent event ID and use it in both client-side and server-side implementations:

<!DOCTYPE html>
<html>
<head>
<!-- Roku Pixel Code -->
<script>
!function(e,r){if(!e.rkp){var t=e.rkp=function(){
var e=Array.prototype.slice.call(arguments)
;e.push(Date.now()),t.eventProcessor?t.eventProcessor.apply(t,e):t.queue.push(e)
};t.initiatorVersion="1.0",t.queue=[],t.load=function(e){
var t=r.createElement("script");t.async=!0,t.src=e
;var n=r.getElementsByTagName("script")[0]
;(n?n.parentNode:r.body).insertBefore(t,n)},rkp.load("https://cdn.ravm.tv/ust/dist/rkp.loader.js")}
}(window,document);
rkp("init","<your id goes here>"),rkp('event', 'PAGE_VIEW');;
</script>
<!-- End Roku Pixel Code -->

<title>Order Confirmation</title>
</head>
<body>
<h1>Thank you for your order!</h1>
<p>Order #ORD-12345 has been confirmed.</p>

<!-- Purchase event tracking with event_id for deduplication -->
<script>
document.addEventListener('DOMContentLoaded', function() {
// Generate a unique event ID that will be used for both client and server side
function generateEventId() {
// Use order ID as base for consistency
var orderId = "ORD-12345";

// Add timestamp for uniqueness
var timestamp = new Date().getTime();

// Add random component to ensure uniqueness
var random = Math.floor(Math.random() * 1000000);

// Combine components to create a unique ID
return orderId + "_" + timestamp + "_" + random;
}

// Generate the event ID
var eventId = generateEventId();

// Store it in a cookie or localStorage for server access if needed
localStorage.setItem('roku_event_id', eventId);

// Order data
var orderData = {
orderId: "ORD-12345",
orderValue: 129.99,
currency: "USD",
products: [
{id: "SKU789012", name: "Wireless Headphones", price: 99.99, quantity: 1},
{id: "SKU345678", name: "Charging Cable", price: 15.00, quantity: 2}
]
};

// Fire the client-side Purchase event with the event_id
rkp('event', 'PURCHASE', {
event_id: eventId, // Include the same event_id here
value: orderData.orderValue,
currency: orderData.currency,
order_id: orderData.orderId,
content_ids: orderData.products.map(function(p) { return p.id; })
});

// Also send this data to your server for server-side event tracking
// The server will use the same event_id when calling the Roku Events API
fetch('/api/track-purchase', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
event_id: eventId, // Include the same event_id here
order_id: orderData.orderId,
value: orderData.orderValue,
currency: orderData.currency,
products: orderData.products
})
});
});
</script>
</body>
</html>

Custom Data Parameters:

Custom Data Parameter

Data type

Description

value

Number

The value of a user performing this event to the business.

Notes:

  • 'Price' is the price for a single item, and 'value' is the total price of the order.

  • ‘Value’ enables ROAS and Order Value reporting fields when passed alongside a PURCHASE event

currency

String

The currency for the value specified (must be a valid currency code)

delivery_category

String

Type of delivery for a purchase event

num_items

Number

Number of items in the event

order_id

String

The order ID for this transaction expressed as a string

contents

Array of objects

Details about the items in the order

purchase_type

String

Type of purchase

content_category

String

Category of the page/product

content_ids

Array of strings

Product IDs associated with the event

content_type

String

Type of content ('product' or 'product_group')

content_name

String

Name of the page/product

predicted_ltv

String

Predicted lifetime value of a subscriber

search_string

String

Search query used

status

String

Status of the action

User Data Parameters

User Data Parameter

Data type

Description

is_hashed

Boolean

Indicates if the user data is hashed

em

String

Email address (preferably hashed)

ph

String

Phone number (preferably hashed)

ge

String

Gender

db

String

Date of birth

ln

String

Last name (preferably hashed)

fn

String

First name (preferably hashed)

ct

String

City (preferably hashed)

st

String

State/province (preferably hashed)

zp

String

Zip/postal code (preferably hashed)

country

String

Country code

external_id

String

External user ID

client_ip_address

String

IP address of the client

client_user_agent

String

User agent of the client

subscription_id

String

Subscription identifier

ga_session_id

String

Google Analytics session ID

ga_client_id

String

Google Analytics client ID

ga_gclid

String

Google Click ID

ga_measurement_ids

Array of strings

Google Analytics measurement IDs`

us_privacy

String

US Privacy string following the IAB CCPA Compliance Framework format (e.g., "1YNN"). This string communicates user privacy preferences according to US privacy regulations like CCPA. See IAB specification

US Privacy String

The us_privacy parameter follows the IAB CCPA Compliance Framework format. This is an industry standard string that communicates user privacy preferences according to US privacy regulations like the California Consumer Privacy Act (CCPA).

The string consists of 4 characters:

  1. Specification Version (1 = Version 1)

  2. Notice/Opportunity to Opt Out (Y = Yes, N = No, - = Not Applicable)

  3. Opt-Out Sale (Y = Yes, N = No, - = Not Applicable)

  4. LSPA Covered Transaction (Y = Yes, N = No, - = Not Applicable)

Example: "1YNN" indicates Version 1, Notice Given, Not Opted Out, Not a Limited Service Provider Agreement transaction.

For more details, refer to the IAB US Privacy String specification.

Example usage:

rkp('event', 'PAGE_VIEW', {
user_data: {
us_privacy: "1YNN", // User received notice, did not opt out
client_ip_address: "192.168.1.1"
}
});

Contents Objects

Object

Data type

Description

id

String

Product identifier (required)

quantity

Number

The quantity of this item (required)

item_price

Number

The price for a single item (required)

delivery_category

String

Delivery method (optional, allowed values: "IN_STORE", "CURBSIDE", "HOME_DELIVERY")

Example code snippet using all custom parameters

rkp('event', 'PURCHASE', {
// Event core attributes
event_id: "purchase-1234567",
event_source: "website",
event_source_URL: "https://www.example.com/checkout/confirmation",
referrer_URL: "https://www.example.com/checkout/payment",

// Custom data
value: 23.98,
currency: "USD",
delivery_category: "IN_STORE",
num_items: 3,
order_id: "ord12345",
content_category: "homewares",
content_ids: ["prod1234", "prod5678"],
content_type: "product_group",
content_name: "plates",
predicted_ltv: "300",
search_string: "New products",
status: "APPROVED",

// Contents details
contents: [
{
delivery_category: "IN_STORE",
id: "prod1234",
item_price: 19.99,
quantity: 1
},
{
delivery_category: "HOME_DELIVERY",
id: "prod5678",
item_price: 3.99,
quantity: 2
}
],

// User data
user_data: {
is_hashed: true,
em: "f660ab912ec121d1b1e928a0bb4bc61b15f5ad44d5efdc4e1c92a25e99b8e44a",
external_id: "user-12345",
client_ip_address: "192.168.1.1",
client_user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
});

Note: Limited Data Use (LDU) is a data processing option that lets you limit how your event data is used in Roku's systems and helps to better support your compliance efforts with various US state privacy laws.

Did this answer your question?