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

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

Set up Segment

This topic describes how setup an integration with Segment and Optimizely.

📘

Note

This is a third-party integration and is not an Optimizely subprocessor. See Optimizely's Third-Party Add-Ons & Platform Integration Terms.

Get started

The first step is to make sure Optimizely Full Stack supports the source type and connection mode you have chosen to implement. To learn more about what dictates the connection modes Segment supports, see Connection Modes.

📘

Note

This page has the most up-to-date information for Optimizely integration with Segment. The Segment-hosted documentation updates less frequently.

WebMobileServer
📱 Device-mode
☁️ Cloud-mode

Segment’s Optimizely Full Stack destination supports the following Optimizely products:

If you are interested in implementing Optimizely Web or Optimizely Full Stack with the JavaScript SDK, please see Segment’s Optimizely Web destination, which supports:

Optimizely Web

Optimizely Full Stack (JavaScript)

Implementation prerequisite

For the integration to work, you will need to implement some of the Optimizely functionality prior to the rest of the integration work.

Although Segment maps track events to Optimizely’s Track method, customers must implement all Optimizely decision-based methods, such as the Activate and Is FeatureEnabled methods, natively. Segment’s API does not include methods that correspond to decision-based methods.

This limitation requires that customers include a native Optimizely implementation before their Segment implementation on pages or in mobile apps where Optimizely experiments run.

Server Side

Getting Started

  1. In your Segment source dashboard, enable the “Optimizely Full Stack” destination (not the “Optimizely Web” destination).
  2. Include your Optimizely project’s projectId and datafile URL in your Segment settings.
  3. Create a native Optimizely instance in your server environment so you can access Optimizely methods like Activate, Is Feature Enabled, etc.
  4. Finally, define any metrics and attributes in your Optimizely dashboard, and to associate metrics with the appropriate Optimizely experiments. Segment maps track event names to Optimizely eventName - the eventName corresponds to an experiment metric. In addition, Segment maps track event context.traits to Optimizely attributes.

📘

Note

If you are using Optimizely SDKs v1.x or v2.x:
If a visitor has any activate or isFeatureEnabled calls, their attributes object for these calls must match the attributes object passed to any track calls for that user id so that it can be correctly attributed on the Optimizely results page.

If you are using Optimizely SDKs v3+, Easy Event Tracking is enabled by default for decision events. For more information, see the Event API.

Set up does not require maintaining the attributes of a user as long as the user id stays the same between Optimizely Activate and Is Feature Enabled calls and Segment track calls to have Optimizely metrics populated in the Optimizely results page. If you would like to segment your Optimizely results by user attribute, then make sure the attributes passed in for the Activate and Is Feature Enabled calls match the attributes passed in for the track calls for that user id.

For more details on how events are attributed on the Optimizely results page, see How Optimizely Counts Conversions.

Example Optimizely implementation

See the example code below for instructions on integrating this SDK with your Segment analytics.

//Node server-side example

const optimizely = require('@optimizely/optimizely-sdk');
const optimizelyEnums = require('@optimizely/optimizely-sdk').enums;
const Analytics = require('analytics-node');

const analytics = new Analytics('YOUR_WRITE_KEY');
const optimizelyClient = optimizely.createInstance({
  sdkKey: '<Your_SDK_Key>',
});

function segmentDecision(decisionObject) {
  var type = decisionObject.type
  //When a decision is generated by a Feature Flag, dispatch an event named Feature Flag, with properties denoting the feature key and other decision information
  if (type == "feature") {
    var info = decisionObject.decisionInfo;
    var featureKeyString = info.featureKey;
    var enabled = info.featureEnabled;
    var attributes = decisionObject.attributes;
    analytics.track('Feature Flag', {
      "key": featureKeyString,
      "enabled": enabled,
      info,
      attributes
    });
    //If the Feature Flag decision is a result of a feature test, dispatch an additional Experiment Viewed semantic event (https://segment.com/docs/connections/spec/ab-testing/)
    if (info.source == "feature-test") {
      var experimentKeyString =info.sourceInfo.experimentKey;
      var experimentVarString = info.sourceInfo.variationKey;
      analytics.track('Experiment Viewed', {
        'experiment_name': experimentKeyString,
        'variation_name': experimentVarString
      })
    }

  }
}

var listenerId = optimizelyClient.notificationCenter.addNotificationListener(
  optimizelyEnums.NOTIFICATION_TYPES.DECISION,
  segmentDecision,
);

Track

Upon invocation of a Segment track event, Segment maps the event to an Optimizely Track event. To ensure that attribution of experiment views and events are consistent in Optimizely, make sure that the same id is used for Activate and Is Feature Enabled method calls:

  • If the Segment event name matches exactly the name of an active experiment metric set up in the Optimizely dashboard;
  • If the experiment metric is associated with a running experiment;
  • If the current user has been assigned a userId via Segment’s identify method (e.g. analytics.identify('123'));
  • If the current user is activated in a running experiment with the associated metric.

Segment also handles the following mapping:

  • Segment track event name to Optimizely eventName.
  • Segment track event properties to Optimizely eventTags.
  • Segment track event context.traits to Optimizely attributes.

revenue values should be passed as a Segment property. The value should be an integer and represent the value in cents, so, for example, $1 should be represented by 100.

📘

Note

Custom Event Tags in Optimizely, which includes any Event Tag outside of revenue or value, will not be displayed on the Optimizely results page but they will be available in a Data Export report.

Segment defaults to identifying users with their anonymousId. Enabling the “Use User ID” setting in your Segment settings means that only track events triggered by identified users are passed downstream to Optimizely. You may optionally fall back to anonymousId when userId is unavailable by setting fallbackToAnonymousId to true.

Android Cloud-mode Implementation

Getting Started

  • In your Segment source dashboard, enable the “Optimizely Full Stack” destination (not the “Optimizely Web” destination).
  • Include the latest version of Optimizely Full Stack’s native SDK in your app-level build.gradle file and implement Optimizely as you would natively.
  • Finally, define any metrics and attributes in your Optimizely dashboard, and associate metrics with the appropriate Optimizely Experiments. Segment maps track event names to Optimizely eventName, which corresponds to an experiment metric. In addition, Segment maps identify traits to Optimizely attributes.

When implementing Optimizely Full Stack via cloud-mode, Segment will map track events to Optimizely track events on our servers and deliver the data to your Optimizely project as usual.

📘

Note

Using Optimizely SDKs v1.x or v2.x require teams to maintain attributes that are passed in for a visitor with any Activate or Is Feature Enabled call to any track made for that user id in order to be attributed on the results page.

When using Optimizely SDKs v3+, Easy Event Tracking, the setup does not require maintaining the attributes of a user as long as the user id stays the same.

For more details on how events are attributed on the Optimizely results page, please refer to the help center documentation on How Optimizely counts conversions.

Example Optimizely implementation

Segment has a semantic event that you can use to track A/B test variations for users.

In the example code below, we add an activate listener block callback to send Segment's A/B event.

import com.segment.analytics.Analytics;
import com.segment.analytics.Properties;


OptimizelyClient optimizelyClient = optimizelyManager.getOptimizely();
// Add a Activate listener
int notificationId = optimizelyClient.getNotificationCenter().addNotificationListener(NotificationCenter.NotificationType.Activate, new ActivateNotificationListener() {
  @Override
  public void onActivate(Experiment experiment,
                    String userId,
                    Map<String, String> attributes,
                    Variation variation) {

    String experimentId = experiment.getId();
    String experimentKey = experiment.getKey();
    String variationId = variation.getId();
    String variationKey = variation.getKey();

    Properties properties = new Properties();
    properties.put("experimentId", experimentId);
    properties.put("experimentName", experimentKey);
    properties.put("variationId", variationId);
    properties.put("variationName", variationKey);

    Analytics.with(getApplicationContext()).track("Experiment Viewed", properties);

  }
});
#import <Analytics/SEGAnalytics.h>
  
NSString *notificationId = [self.optimizely.notificationCenter addDecisionNotificationListenerWithDecisionListener:^(NSString *type, NSString *userId, NSDictionary<NSString *,id> *attributes, NSDictionary<NSString *,id> *decisionInfo) {
       NSDictionary *properties = @{
           @"type" : [experiment experimentId,
           @"userId" : userId,
           @"attributes" : attributes,
           @"decisionInfo" : decisionInfo
           };
       [[SEGAnalytics sharedAnalytics] track:@"Experiment Viewed" properties:properties];
}];

Track

Upon invocation of a Segment track event, Segment maps the event to an Optimizely track event:

  • If the Segment event name matches exactly the name of an active experiment metric set up in the Optimizely dashboard;
  • If the experiment metric is associated with a running experiment;
  • If the current user is activated in a running experiment with the associated metric.

Segment also handles the following mapping:

  • Segment track event name to Optimizely eventName.
  • Segment track event properties to Optimizely eventTags.
  • Segment track event context.traits to Optimizely attributes.

revenue values should be passed as a Segment property. The value should be an integer and represent the value in cents, so, for example, $1 should be represented by 100.

Segment defaults to identifying users with their anonymousId. Enabling the “Use User ID” setting in your Segment settings means that only track events triggered by identified users are passed downstream to Optimizely. You may optionally fall back to anonymousId when userId is unavailable by setting fallbackToAnonymousId to true.

Identify

Invoking a Segment identify event sets Segment traits as Optimizely attributes. The attributes are sent downstream to Optimizely upon invocation of the next Segment track event.

Reset

Invoking this method invalidates the listener for the Experiment Viewed event.

iOS Cloud-mode Implementation

Getting Started

  • In your Segment source dashboard, enable the “Optimizely Full Stack” destination (not the “Optimizely Web” destination).
  • Include the latest version of Optimizely Full Stack’s native SDK in your app and implement it as you would natively.
  • Finally, define any metrics and attributes in your Optimizely dashboard, and associate metrics with the appropriate Optimizely Experiments. Segment maps track event names to Optimizely eventName, which corresponds to an experiment metric. In addition, Segment maps identify traits to Optimizely attributes.

When implementing Optimizely via cloud-mode, Segment will map track events to Optimizely track events on our servers and deliver the data to your Optimizely project as usual.

📘

Note

Using Optimizely SDKs v1.x or v2.x require teams to maintain attributes that are passed in for a visitor with any Activate or Is Feature Enabled call to any track made for that user id in order to be attributed on the results page.

When using Optimizely SDKs v3+, Track events setup does not require maintaining the attributes of a user as long as the user id stays the same.

For more details on how events are attributed on the Optimizely results page, please refer to the help center documentation on how Optimizely counts conversions.

Example Optimizely implementation

Segment has a semantic event that you can use to track A/B test variations for users.

In the example code below, we add an activate listener block callback to send Segment's A/B event.

import Analytics

let notificationId = optimizely.notificationCenter.addDecisionNotificationListener(decisionListener: { (type, userId, attributes, decisionInfo) in
 		let properties: [String: Any] = ["type": type,
                  "userId": userId,
                  "attributes": attributes,
                  "decisionInfo": decisionInfo]
    
   	SEGAnalytics.shared().track("Experiment Viewed", properties: properties)
})
#import <Analytics/SEGAnalytics.h>
  
NSString *notificationId = [self.optimizely.notificationCenter addDecisionNotificationListenerWithDecisionListener:^(NSString *type, NSString *userId, NSDictionary<NSString *,id> *attributes, NSDictionary<NSString *,id> *decisionInfo) {
       NSDictionary *properties = @{
           @"type" : [experiment experimentId,
           @"userId" : userId,
           @"attributes" : attributes,
           @"decisionInfo" : decisionInfo
           };
       [[SEGAnalytics sharedAnalytics] track:@"Experiment Viewed" properties:properties];
}];

Track

Upon invocation of a Segment track event, Segment maps the event to an Optimizely track event:

  • If the Segment event name matches exactly the name of an active experiment metric set up in the Optimizely dashboard;
  • If the experiment metric is associated with a running experiment;
  • If the current user is activated in a running experiment with the associated metric.

Segment also handles the following mapping:

  • Segment track event name to Optimizely eventName.
  • Segment track event properties to Optimizely eventTags.

revenue values should be passed as a Segment property. The value should be an integer and represent the value in cents, so, for example, $1 should be represented by 100.

Segment defaults to identifying users with their anonymousId. Enabling “Use User ID” setting in your Segment dashboard means that only track events triggered by identified users are passed downstream to Optimizely. You may optionally fall back to anonymousId when userId is unavailable by setting fallbackToAnonymousId to true.

Identify

Invoking a Segment identify event sets Segment traits as Optimizely attributes. The attributes are sent downstream to Optimizely upon invocation of the next Segment track event.

Personas

Please follow these instructions on how to setup Personas and Optimizely:

GDPR Support

Segment supports deleting/suppressing users in Optimizely via the Segment app. In order to do this however, you will need to create a Personal Access Token in Optimizely and provide it as the value of the Access Token setting.

Supported Sources and Connection Modes

The first step is to make sure Optimizely Full Stack supports the source type and connection mode you have chosen to implement. You can learn more about what dictates the connection modes we support here.

To learn more about Connection Modes and what dictates which we support, see here.

WebMobileServer
📱 Device-mode
☁️ Cloud-mode

Segment offers an optional Device-based Connection Mode for Mobile data going to Optimizely Full Stack, so that you can use Optimizely Full Stack features that collect data directly from the mobile device. To do this, you must package the Segment-Optimizely Full Stack mobile SDK with the Segment mobile SDK.

Settings

Segment lets you change these destination settings from your Segment dashboard without having to touch any code.

Account ID

In order to use Optimizely via server-side, you must enter your Account ID from your Optimizely account. You can find this ID by visiting app.optimizely.com/v2/accountsettings/account-number/plan

Cache Exp

To optimize the server-side integration, we will cache the fetched datafile that you have provided for this amount of time (in seconds) in Redis. Since the datafile should not change unless you modified the conditions or variation rules of your experiments, it is advised to have a minimum floor of 300 seconds (5 minutes).

Datafile URL

In order to use Optimizely server-side, you must enter the entire URL for your datafile. It should look something like https://cdn.optimizely.com/json/9218021209.json.

Fall Back To Anonymous Id

Optionally fall back to anonymousId when userId is not present.

Only Track Known Users

Optimizely does not alias known and unknown users. By default, Segment will only send the anonymousId to Optimizely. Enable this to only send the userId to Optimizely. Important: This setting only applies if you are bundling this integration for mobile sources.

Sends the experiment and variation information as properties on a track call.

Send experiment data to other tools (as a track call). An “Experiment Viewed” track event will be triggered each time you access an Optimizely live variable. If you’re regularly accessing live variables and want to reduce the number of track events triggered, pass the “false” flag, for example, our Android library would be:

Boolean myVariable = optimizelyClient.getVariableBoolean("myVariable", userId, false);

​And for our iOS library:

bool myVariable = [optimizely variableBoolean:@"myVariable" 
                                               userId:userId] 
                                               activateExperiment:False];

Specifies the Experiment Viewed as a non-interaction event for Google Analytics

Send Experiment Viewed as a non-interaction event

Use Optimizely SDKs v3+

Enable this setting to instantiate an Optimizely client using v3.2.2 of Optimizely’s SDK. The default Optimizely client version Segment instantiates is v2.1.3. NOTE: Do not enable this setting if the SDK version you are using to activate users into your Optimizely experiments is less than 3.0. You can find more information on how migrating from Optimizely 2.x to 3.x will affect your experiment tracking in Optimizely’s documentation.

Use Optimizely User ID

Enable this if you want the server-side integration to use Optimizely User ID instead of User ID or anonymous ID in your calls

Use User ID

Enable this if you want the server-side integration to use User ID instead of anonymous ID in your identify calls

Adding Optimizely Full Stack to the integrations object

To add Optimizely Full Stack to the integrations JSON object (for example, to filter data from a specific source), use one of the following valid names for this integration:

  • Optimizely X
  • Optimizely Full Stack