Optimizely will be sunsetting Full Stack Experimentation on July 29, 2024. See the recommended Feature Experimentation migration timeline and documentation.

Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

JavaScript (Browser)

Quickstart guide for Optimizely Full Stack

Welcome to the quickstart guide for Optimizely's Full Stack JavaScript (Browser) SDK. Follow the steps in the guide below to roll out a feature and start your first experiment. You will need an account to follow this guide, if you do not have one yet, you can register for a free account on Optimizely.com.

Steps:

  1. Install the SDK
  2. Instantiate Optimizely in your app
  3. Create a feature flag (with variable) in Optimizely
  4. Implement the feature in your app
  5. Create an event to track in Optimizely
  6. Implement event tracking in your app
  7. Launch the experiment for your feature!

Skip to full code examples

To see a complete code example you can run after you set up this quickstart's experiment in the Optimizely app.

1. Install the SDK

Run without installingRun locally
If you want to run in a demo environment, for example CodePen, without installing the SDK locally, use the following HTML script tag examples.If you want to run using Node (best practice), then use the following NPM examples.
<!-- create a blank project in CodePen or serve a blank index.html locally and add the following content: -->

<html>
  <head>
    <!--install Optimizely-->
   <script src="https://unpkg.com/@optimizely/[email protected]/dist/optimizely.browser.umd.min.js"></script>
  </head>
  <body>
    <h1>Hello World</h1>
    <p id="subtitle">We will use this subtitle to show flag status</p>
  </body>
</html>
# From an empty project directory, create an optimizely.js file, and run the terminal command below to install Optimizely Full Stack: 
npm install --save @optimizely/optimizely-sdk
# From your project directory, run the terminal command below to install Optimizely Full Stack: 
yarn add @optimizely/optimizely-sdk

2. Instantiate Optimizely

<!--step 1: in add your datafile using your SDK key so you can later instantiate an Optimizely client -->
<!--in an index.html, add a <script> tag in your <head> tag: -->

<script src="https://cdn.optimizely.com/datafiles/<Your_SDK_KEY>.json/tag.js"></script>

<!--step 2. after the <body> tag, add a new <script> tag to instantiate an Optimizely client  from the datafile:-->

<script>
    var optimizelyClientInstance = optimizelySdk.createInstance({
        datafile: window.optimizelyDatafile,
    });
</script>
// instantiate an Optimizely client using your SDK key
// in an optimizely.js file:

const optimizelySDK = require('@optimizely/optimizely-sdk');
const optimizelyClientInstance = optimizelySDK.createInstance({
sdkKey: '<Your_SDK_Key>'
    });

Remember to replace <Your_SDK_Key> with your own.

To find your SDK Key in your Optimizely project:

  1. Navigate to Settings > Primary Environment
  2. Copy the SDK Key
2850

Click image to enlarge

📘

Note

Notice that each environment has its own SDK key.

3. Create a feature flag

A feature flag lets you control which users are exposed to a new feature in your app. For this quickstart, imagine that you run an online store and you’re rolling out a new ‘discount’ feature that shows different discounts to try to increase sales. Create a feature in Optimizely named ‘discount’ and give it a variable named ‘amount’.

Create a feature flag in your Optimizely project:

  1. Navigate to Features > New Feature.
  2. Name the feature key discount
  3. Click Add Variable
  4. Name the variable amount
  5. Set the variable type to "Integer"
  6. Set the variable default value to 5 (this represents $5)
  7. Skip the rest of the dialog and click Create Feature.

Here is a visual for how to set it up:

1246

Click image to enlarge

4. Implement the feature

Next, use the SDK’s Is Feature Enabled method to determine whether to show or hide the discount feature for a specific user. You can roll out the discount feature to a percentage of traffic and run an experiment to show different discounts to just a portion of users. Once you learn which discount value works best to increase sales, roll out the discount feature to all traffic with the amount set to the optimum value.

// add in your index.html, in the <script> tag where you run optimizelySdk.createInstance
var enabled = optimizelyClientInstance.isFeatureEnabled('discount', userId);
// add in the optimizely.js file:
const enabled = optimizelyClientInstance.isFeatureEnabled('discount', userId);

Even before you decide which discount amounts to test, you can code logic for exposing them. You can set the different discount values at any time in Optimizely (we’ll set them in the last step). For now, use the Get Feature Variable method to return the discount amount for a specific user.

// add in your index.html, in the <script> tag where you run optimizelySdk.createInstance
    if (enabled) {
        const discountAmount = optimizelyClientInstance.getFeatureVariable('discount', 'amount', userId);
        document.querySelector("#subtitle").innerText = userId + " got a discount of " + discountAmount
    } else {
        document.querySelector("#subtitle").innerText = userId + "did not get the discount (flag disabled)"
    }
// add in the optimizely.js file:
if (enabled) {  
  const discountAmount = optimizelyClientInstance.getFeatureVariable('discount', 'amount', userId);
  console.log(`${userId} got a discount of $${discountAmount}`);
} else {
  console.log(`${userId} did not get the discount (flag disabled)`);
}

5. Create an event

In Optimizely, you will use event tracking to measure the performance of your experiments. Exposing users to new features influences them to behave in different ways. Tracking the users’ relevant actions is how we capture the impact those features had. This means we need to define which actions we want to track.

Since we are experimenting with a new discount feature it makes sense to track if the user goes on to make a purchase after they’ve been shown a discount.

Create an event named ‘purchase’ in your Optimizely project:

  1. Navigate to Events > New Event
  2. Set the event key to purchase
  3. Click Create Event
894

Click image to enlarge

6. Implement event tracking

You need a way to tell Optimizely when a user has made a purchase in your app and map this event in your app code to the specific event you created in Optimizely. Luckily the SDK has a method for that! Simply use the ‘track’ method on the SDK client and pass in the key for the event you created (‘purchase’) and the userId.

// add in your index.html, in the <script> tag where you run optimizelySdk.createInstance
optimizelyClientInstance.track('purchase', userId);
// add in optimizely.js
optimizelyClientInstance.track('purchase', userId);

7. Launch the experiment

At this point, you have set up almost everything we need to run your Full Stack experiment. You have:

  • Set up feature flag (with variable)
  • Implemented dynamic serving of the feature & variable in the app
  • Set up an event to track the impact of the feature
  • Implemented tracking of purchase events in the app

The only thing left to set up is the experiment itself! To create an experiment in your Optimizely project:

  1. Navigate to Experiments
  2. Click Create New > Feature Test
  3. In the Feature box, select the discount feature
  4. Click Create Feature Test
325

Click image to enlarge

710

Click image to enlarge

By default, Optimizely creates an experiment with two variations: one with the feature on and one with the feature off. Toggling the feature on for both variations will cause Optimizely to show the discounts to all users who are part of the experiment (a single user only ever sees one variation).

  1. Toggle the feature on for both variations
  2. For variation_1 set the discount value to 5
  3. For variation_2 set the discount value to 10
  4. Click Save to save your changes
704

Click image to enlarge

Next, click on Metrics in the left side-panel and add your new purchase event as a metric for your experiment and save to your experiment.

1267

Click image to enlarge

1264

Click image to enlarge

Now click Run in the top left of the experiment page in your chosen environment and your experiment will start.

382

Click image to enlarge

📘

Note

To test the different variations of the experiment, you’ll need to pass in unique userIds to the SDK methods. One way to do this is to use a random number generator to pass in random userIds.

Congratulations! You have successfully set up and launched your first Optimizely Full Stack experiment. While this example focused on optimizing sales, Optimizely’s experimentation platform can support an open-ended set of experimentation use cases.

Review our documentation for more info and to learn more ways to optimize your software using experimentation.

Complete code sample

Here is a runnable code example that wraps up everything we have covered in this quickstart, with some additional options.

<html>

<!--  To run in a demo environment without installing the SDK locally:
   1. Create a blank codepen 
   2. Copy this code sample into the HTML pane in codepen, and replace <Your_SDK_Key>
   3. Reload your codepen by making a trivial edit to the HTML (such as adding a space).
   4. Click the 'purchase' button to mock experiment results
   5. Repeat step 4. a few times, then head over to the Optimizely app to view your experiment results
 -->

<head>
  <title>Hello world</title>
  <!-- Install Optimizely SDK -->
  <script src="https://unpkg.com/@optimizely/optimizely-sdk/dist/optimizely.browser.umd.min.js"></script>
  <!-- Add your datafile using your SDK key so you can later instantiate an  Optimizely client -->
  <script src="https://cdn.optimizely.com/datafiles/<Your_Sdk_Key>.json/tag.js"></script>
</head>

<body>  
  <h1>Hello world</h1>  
  <p id="subtitle">We will use this subtitle to show flag status</p>
  <button>Click to mock their purchase</button>
</body>

<script>
  // instantiate an Optimizely client from the datafile
  var optimizelyClientInstance = window.optimizelySdk.createInstance({
    datafile: window.optimizelyDatafile
  });
  /* --------------------------------
     OPTIONAL: Add a notification listener so you can later integrate with third party analytics platforms
     --------------------------------
     */
  var listenerId = optimizelyClientInstance.notificationCenter.addNotificationListener(
    window.optimizelySdk.enums.NOTIFICATION_TYPES.DECISION,
    function(decision) {
      console.log(
        `NOTIFICATION LISTENER: User bucketing event for:
              User: ${decision.userId}
              Variation: ${decision.decisionInfo.sourceInfo["variationKey"]}
              Experiment: ${decision.decisionInfo.sourceInfo["experimentKey"]}`);
      // send decision to an anayltics platform here
    }
  );
  /* --------------------------------
     OPTIONAL: to get rapid demo experiment results, generate random user ids so a user gets randomly bucketed into a variation every time you rerun
     --------------------------------
   */
  function makeid() {
    var userId = "";
    userId = String(Math.random());
    return userId;
  };
  // make a random user ID
  var userId = makeid();
  /* --------------------------------
     Bucket user into a flag variation and mock experiment results
     --------------------------------
     */
  // get flag enabled status
  var enabled = optimizelyClientInstance.isFeatureEnabled('discount', userId);
  if (enabled) {
    // get the flag variable value, as determined by the variation the user buckets into
    const discountAmount = optimizelyClientInstance.getFeatureVariable('discount', 'amount', userId);
    document.querySelector("#subtitle").innerText = "user number " + userId + " got a discount of " + discountAmount
  } else {
    document.querySelector("#subtitle").innerText = "user number " + userId + "  did not get a discount (flag disabled)"
  }
  const button = document.querySelector('button')
  button.addEventListener('click', function(e) {
    optimizelyClientInstance.track('purchase', userId);
    console.log("Optimizely tracked a purchase event to show in experiment results")
  })
</script>

</html>
/*  To install SDK and run locally:
   1. Create an empty project directory. For example, run in the terminal: touch opty-demo
   2. Create an empty package.json. Run: npm init. Leave all the prompts blank
   3. Create optimizely.js: run: touch optimizely.js. 
   4. Copy this code sample into optimizely.js and replace <Your_SDK_Key>
   5. Run: npm install --save @optimizely/optimizely-sdk
   6. Run: node optimizely.js. Answer the prompt to mock experiment results, then press Ctl+C twice to exit
   7. Repeat step 6 a few times, then head over to the Optimizely app to see experiment results
 */

const optimizelySDK = require('@optimizely/optimizely-sdk');
const enums = optimizelySDK.enums;
const optimizelyClientInstance = optimizelySDK.createInstance({
  sdkKey: '<Your_Sdk_Key'
});

//accept CLI user input (to mock event tracking)
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})

optimizelyClientInstance.onReady().then(() => {
  //optimizelyClientInstance downloaded your Optimizely configuration
  console.log('Optimizely client ready');
  /* --------------------------------
     OPTIONAL: Add a notification listener so you can later integrate with third party analytics platforms
     --------------------------------
   */
  const listenerId = optimizelyClientInstance.notificationCenter.addNotificationListener(enums.NOTIFICATION_TYPES.DECISION,
    function (decision) {
      console.log(
        `Notification listener: User bucketing event for:
                User: ${decision.userId}
                Variation: ${decision.decisionInfo.sourceInfo["variationKey"]}
                Experiment: ${decision.decisionInfo.sourceInfo["experimentKey"]}`);
      // send decision to an analytics platform here
    }
  );
  
    /* --------------------------------
       OPTIONAL: to get rapid demo experiment results, generate random userIds so a new user gets bucketed into a variation every time you rerun
       --------------------------------
    */ 
  function makeid() {
    var userId = "";
    userId = String(Math.random());
    return userId;
  };
  // make a random user ID
  const userId = makeid();

      /* --------------------------------
       Bucket user into a flag variation and mock experiment results
       --------------------------------
     */ 

  // get flag enabled status
  const enabled = optimizelyClientInstance.isFeatureEnabled('discount', userId);
  if (enabled) {
    // get the flag variable value, as determined by the variation the user buckets into
    const discountAmount = optimizelyClientInstance.getFeatureVariable('discount', 'amount', userId);
    console.log("user number " + userId + " got a discount of " + discountAmount);
    readline.question('Pretend they made a purchase? y/n', (answer) => {
      if (answer == 'y') {
        optimizelyClientInstance.track('purchase', userId);
        console.log("Optimizely recorded a purchase in experiment results")
      }
      else {
        console.log("Optimizely didn't record a purchase in experiment results")
      }
      readline.close()
    })

  } else {
    console.log("user number " + userId + " didn't get a discount (flag disabled)")
    readline.question('Pretend that they made a purchase? y/n', (answer) => {
      if (answer == 'y') {
        optimizelyClientInstance.track('purchase', userId);
        console.log("Optimizely recorded a purchase in experiment results")
      }
      else {
        console.log("Optimizely didn't record a purchase in experiment results")
      }
      readline.close()
    })
  }

}).catch(error => {
  console.log("Error: " + error)
});

Next

For more information, view our full JavaScript (Browser) SDK documentation