Example usage of the JavaScript SDK v6+
A code example of how to use the Optimizely Feature Experimentation JavaScript SDK to evaluate feature flags, activate A/B tests, or feature tests.
After you have installed the JavaScript SDK, imported the Optimizely Feature Experimentation library into your code, acquired your project's datafile, and instantiated a client, you can use the client to evaluate flag rules, including A/B tests, flag deliveries, and run a multi-armed bandit optimization.
Version
v6.0.0+
For versions 5.3.5 and below, see JavaScript (Browser) SDK or JavaScript (Node) SDK. See the SDK compatibility matrix documentation for a list of current SDK releases and the features they support.
Example
This example walks through the following three key steps:
- Evaluate a flag with the key
product_sortusing the decide method. This also sends a decision event to Optimizely to record that the user was exposed to the experiment. - Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
- Check the flag's enabled state and read a configuration variable (
sort_method) to determine which experience the user gets. - Check the flag variation directly and run the corresponding control or variation code.
- Check the flag's enabled state and read a configuration variable (
- Track a conversion event called
purchasedto measure the experiment's impact. The track event method ties the purchase back to the A/B test and sends it to Optimizely so it displays on your Experiment Results page.
WarningDO NOT use the unpkg CDN and the using HTML script tags example in production environments.
If you rely on unpkg URLs without specifying the package version, your application may unexpectedly break when a new major version of the JavaScript SDK is published to npm, even if you did not explicitly upgrade.
unpkg is a public CDN for open-source packages published to npm. It
- has no uptime guarantees.
- automatically serves the latest version of an npm package when no version is specified in the url, including breaking major version changes.
If you still decide to use unpkg in production, ensure that the version of the SDK is specified in the URL.
import {
createBatchEventProcessor,
createInstance,
createOdpManager,
createPollingProjectConfigManager,
} from "@optimizely/optimizely-sdk";
const SDK_KEY="YOUR_SDK_KEY";
const pollingConfigManager = createPollingProjectConfigManager({
sdkKey: SDK_KEY,
autoUpdate: true,
updateInterval: 60000, // 1 minute
});
const batchEventProcessor = createBatchEventProcessor();
const odpManager = createOdpManager();
const optimizelyClient = createInstance({
projectConfigManager: pollingConfigManager,
eventProcessor: batchEventProcessor,
odpManager: odpManager,
});
optimizelyClient.onReady().then(() => {
const attributes = { logged_in: true };
const user = optimizelyClient.createUserContext('user123', attributes);
if (!user) {
throw new Error('failed to create user context');
}
const decision = user.decide('product_sort');
const variationKey = decision['variationKey'];
if (variationKey === null) {
console.log(' decision error: ', decision['reasons']);
}
const enabled = decision['enabled'];
if (enabled) {
const sortMethod = decision.variables['sort_method'];
// execute code for sort method value
}
if (variationKey === 'control') {
// Execute code for control variation
} else if (variationKey === 'treatment') {
// Execute code for treatment variation
}
// Track an event
user.trackEvent('purchased');
}).catch((err) => {
// handle error
});
<html>
<head>
<title>Hello world</title>
<!-- Install Optimizely SDK -->
<!-- Replace VERSION_NUMBER with the JavaScript SDK version you want to use. -->
<script src="https://unpkg.com/@optimizely/optimizely-sdk@VERSION_NUMBER/dist/optimizely.browser.umd.min.js"></script>
</head>
<body>
<h1>Hello world</h1>
</body>
<script>
// instantiate an Optimizely client from the datafile
const {
createPollingProjectConfigManager,
createBatchEventProcessor,
createOdpManager,
} = window.optimizelySdk;
const SDK_KEY="YOUR_SDK_KEY";
const pollingConfigManager = createPollingProjectConfigManager({
sdkKey: SDK_KEY,
autoUpdate: true,
updateInterval: 60000, // 1 minute
});
const batchEventProcessor = createBatchEventProcessor();
const odpManager = createOdpManager();
const optimizelyClient = window.optimizelySdk.createInstance({
projectConfigManager: pollingConfigManager,
eventProcessor: batchEventProcessor,
odpManager: odpManager,
});
if (optimizelyClient) {
optimizelyClient.onReady().then(() => {
const attributes = { logged_in: true };
const user = optimizelyClient.createUserContext('user123', attributes);
if (!user) {
throw new Error('failed to create user context');
}
const decision = user.decide('product_sort');
const variationKey = decision['variationKey'];
if (variationKey === null) {
console.log(' decision error: ', decision['reasons']);
}
const enabled = decision['enabled'];
if (enabled) {
const sortMethod = decision.variables['sort_method'];
// execute code for sort method value
}
if (variationKey === 'control') {
// Execute code for control variation
} else if (variationKey === 'treatment') {
// Execute code for treatment variation
}
// Track an event
user.trackEvent('purchased');
}).catch((err) => {
// handle error
});
} else {
// there was an error creating the instance, handle error
}
</script>
</html>Updated 3 days ago
