Web Experimentation JavaScript API Reference
Overview
Section titled “Overview”The window.optimizely JavaScript API lets you interact with Optimizely Web Experimentation from custom code on your website. You use it to activate experiments, send custom events, identify users, manage opt-out preferences, and control page activation.
All commands are sent through window.optimizely.push, which accepts an action object. The push-based pattern ensures commands are queued if the Optimizely snippet has not finished loading yet.
API pattern
Section titled “API pattern”Every API call follows the same pattern:
window.optimizely = window.optimizely || [];window.optimizely.push({ type: '<action_type>', // ... action-specific parameters});Always initialize the array before pushing to avoid errors if the Optimizely snippet loads after your code.
activate
Section titled “activate”Manually activates an experiment or campaign. Use this when the experiment’s activation conditions are set to “Manual” in the Optimizely app and you want to control exactly when the experiment runs.
// Activate a specific campaign by ID
window.optimizely.push({
type: 'activate',
campaignId: '21938470052',
});
// Activate all experiments on the current page
window.optimizely.push({
type: 'activate',
}); | Parameter | Type | Required | Description |
|---|---|---|---|
campaignId | string | No | The campaign ID to activate. If omitted, all eligible experiments on the current page are activated. |
When to use
Section titled “When to use”- Your experiment targets a single-page application (SPA) where URL changes do not trigger a full page load.
- You want to delay experiment activation until a specific element is visible or a user action occurs.
- You manage page routing with a framework like React Router or Next.js and need to re-evaluate experiments on virtual navigation.
Sends a custom event to Optimizely for tracking conversions. Events must be created in the Optimizely app before they can be tracked.
// Track a simple event
window.optimizely.push({
type: 'event',
eventName: 'add_to_cart',
});
// Track with tags (revenue in cents)
window.optimizely.push({
type: 'event',
eventName: 'purchase_completed',
tags: {
revenue: 4999, // $49.99 in cents
value: 49.99, // Numeric value for aggregation
product_id: 'SKU-123',
},
}); | Parameter | Type | Required | Description |
|---|---|---|---|
eventName | string | Yes | The event key as defined in the Optimizely app under Events. Case-sensitive. |
tags | object | No | Key-value pairs attached to the event. revenue (integer, in cents) and value (float) are reserved for revenue metrics. Custom tags are stored for data export. |
Reserved tag names
Section titled “Reserved tag names”| Tag | Type | Description |
|---|---|---|
revenue | integer | Revenue in cents. Used by revenue metrics in Optimizely results. |
value | number | A numeric value for aggregation. Used by numeric metrics in results. |
Activates a page in the Optimizely project. Use this to trigger experiments on pages in single-page applications where URL changes do not cause a full page reload.
// Activate a page by its API name
window.optimizely.push({
type: 'page',
pageName: 'product_detail_page',
});
// Activate with tags for custom analytics
window.optimizely.push({
type: 'page',
pageName: 'checkout_step_2',
tags: {
category: 'checkout',
step: 2,
},
}); | Parameter | Type | Required | Description |
|---|---|---|---|
pageName | string | Yes | The API name of the page as defined in the Optimizely app under Pages. |
tags | object | No | Key-value pairs sent with the page activation event. |
SPA integration
Section titled “SPA integration”For single-page applications, call page whenever the user navigates to a new view. This ensures experiments targeting that page are activated and impressions are tracked correctly.
// Example: React Router integrationimport { useEffect } from 'react';import { useLocation } from 'react-router-dom';
function OptimizelyPageTracker() { const location = useLocation();
useEffect(() => { const pageMap = { '/products': 'product_listing_page', '/cart': 'cart_page', '/checkout': 'checkout_page', };
const pageName = pageMap[location.pathname]; if (pageName) { window.optimizely = window.optimizely || []; window.optimizely.push({ type: 'page', pageName }); } }, [location]);
return null;}Identifies the current visitor with a user ID and optional attributes. Attributes are used for audience targeting in experiments.
// Set the user ID (for cross-device tracking)
window.optimizely.push({
type: 'user',
userId: 'user-42',
});
// Set user attributes for audience targeting
window.optimizely.push({
type: 'user',
userId: 'user-42',
attributes: {
plan: 'enterprise',
country: 'US',
lifetime_value: 1250,
is_beta_tester: true,
},
}); | Parameter | Type | Required | Description |
|---|---|---|---|
userId | string | No | A stable user identifier. When set, Optimizely uses this for bucketing instead of the anonymous visitor ID. Enables cross-device consistency. |
attributes | object | No | A map of attribute names to values. Attribute names must match those defined in Audiences > Attributes in the Optimizely app. |
When to call
Section titled “When to call”- On login — Set
userIdwhen the user authenticates so experiments are consistent across sessions and devices. - On page load — Set attributes from your backend (plan type, account age, etc.) before experiments activate.
- Before activation — Attributes must be set before experiments are activated for audience conditions to evaluate correctly.
opt-out
Section titled “opt-out”Opts the current visitor out of all Optimizely experiments. When opted out, no experiments run and no events are tracked. The opt-out state is stored in a cookie and persists across page loads.
// Opt the user out of all experiments
window.optimizely.push({
type: 'optOut',
isOptOut: true,
});
// Opt the user back in
window.optimizely.push({
type: 'optOut',
isOptOut: false,
});
// Check opt-out status
const state = window.optimizely.get('state');
const isOptedOut = state.getRedirectInfo().isOptedOut; | Parameter | Type | Required | Description |
|---|---|---|---|
isOptOut | boolean | Yes | true to opt out, false to opt back in. |
Use cases
Section titled “Use cases”- Cookie consent — Opt users out when they decline analytics cookies.
- Internal traffic — Opt out employees or QA testers to avoid polluting experiment results.
- Privacy compliance — Integrate with your consent management platform (CMP) to respect user choices.
disable
Section titled “disable”Disables the Optimizely snippet entirely for the current page. No experiments run, no events are sent, and no cookies are written. Unlike optOut, this does not persist across page loads.
// Disable Optimizely on this page
window.optimizely.push({
type: 'disable',
}); Use disable when you need to prevent Optimizely from running on specific pages (for example, checkout confirmation pages where script execution must be minimal).
Reading state
Section titled “Reading state”Use window.optimizely.get to read the current state of the Optimizely client.
// Get the current state object
const state = window.optimizely.get('state');
// Get active experiments
const activeExperiments = state.getActiveExperimentIds();
console.log('Active experiments:', activeExperiments);
// Get the variation for a specific experiment
const variationMap = state.getVariationMap();
for (const [experimentId, variation] of Object.entries(variationMap)) {
console.log(`Experiment ${experimentId}: variation ${variation.id} (${variation.name})`);
}
// Get the current visitor ID
const visitorId = state.getVisitorId();
console.log('Visitor ID:', visitorId);
// Get page states
const pageStates = state.getPageStates();
for (const [pageId, pageState] of Object.entries(pageStates)) {
console.log(`Page ${pageId}: ${pageState.apiName} — active: ${pageState.isActive}`);
} State methods
Section titled “State methods”| Method | Returns | Description |
|---|---|---|
getActiveExperimentIds() | string[] | IDs of experiments currently active for this visitor. |
getVariationMap() | object | Map of experiment IDs to variation objects with id and name. |
getVisitorId() | string | The anonymous visitor ID stored in the Optimizely cookie. |
getPageStates() | object | Map of page IDs to page state objects with apiName and isActive. |
getRedirectInfo() | object | Information about redirect experiments, including whether the visitor was redirected. |
getCampaignStates() | object | Map of campaign IDs to their current state, including variation assignment and activation status. |
Snippet loading
Section titled “Snippet loading”The Optimizely snippet should be loaded synchronously in the <head> of your page to prevent flicker. The push-based API ensures commands are queued even if the snippet has not finished executing.
<!-- Load the Optimizely snippet synchronously --><script src="https://cdn.optimizely.com/js/YOUR_PROJECT_ID.js"></script>
<!-- Your code can push commands immediately --><script> window.optimizely = window.optimizely || []; window.optimizely.push({ type: 'user', attributes: { plan: 'enterprise' }, });</script>If you load the snippet asynchronously (with async or defer), visitors may see the original page content before the experiment variation is applied. This is called flicker. Use the Optimizely anti-flicker snippet or synchronous loading to avoid it.