Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.

Dev guideRecipesAPI ReferenceChangelog
Dev guideAPI ReferenceRecipesChangelogUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev guide

Example usage of the JavaScript SDK v6

A code example of how to use the Optimizely Feature Experimentation JavaScript (Browser) SDK to evaluate feature flags, activate A/B tests, or feature tests.

❗️

Warning

This content covers the Feature Experimentation JavaScript (Browser) SDK v6 features currently in pre-production testing and is subject to change before release

For the latest released version, see JavaScript (Browser) SDK.

After you have installed the JavaScript (Browser) SDK, import the Optimizely Feature Experimentation library into your code, get your Optimizely Feature Experimentation project's datafile, and instantiate a client you can use the client to evaluate flag rules, including A/B tests and flag deliveries.

Version

v6.0.0+

Example

This code example demonstrates the basic usage of each of the following concepts:

  • Evaluate a flag with the key product_sort using the Decide method. As a side effect, the Decide function also sends a decision event to Optimizely Feature Experimentation to record that the current user was exposed to the experiment.
  • Conditionally execute your feature code. You have a couple of options.
    • Fetch the flag-enabled state, then check a configuration variable on the flag called sort_method. The SDK evaluates your flag rules and determines what flag variation the user is in and, therefore, which sort method variable they should see.
    • Fetch on the flag variation, then run the 'control' or 'variation' code.
  • Use event tracking to track an event called purchased. This conversion event measures the impact of an experiment. Using the Track Event method, the purchase is automatically attributed back to the running A/B test for which we made a decision, and the SDK sends a network request to Optimizely Feature Experimentation through the customizable event dispatcher so Optimizely can count it in your results page.
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,
});

if (optimizely) {
  optimizely.onReady().then(() => {
    const attributes = { logged_in: true };
    const user = optimizely.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 constiation
    } else if (variationKey === 'treatment') {
      // Execute code for treatment constiation
    }

    // Track an event
    user.trackEvent('purchased');
  }).catch((err) => {
    // handle error
  });
} else {
  // there was an error creating the instance, handle error
};

<html>

<head>
  <title>Hello world</title>
  <!-- Install Optimizely SDK -->
  <script src="https://unpkg.com/@optimizely/optimizely-sdk/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 constiation
      } else if (variationKey === 'treatment') {
        // Execute code for treatment constiation
      }

      // Track an event
      user.trackEvent('purchased');
    }).catch((err) => {
      // handle error
    };
  } else {
    // there was an error creating the instance, handle error
  };
</script>

</html>