Dev guideAPI Reference
Dev guideAPI ReferenceUser GuideGitHubNuGetDev CommunitySubmit a ticketLog In
GitHubNuGetDev CommunitySubmit a ticket

Set up Segment

This topic describes how to set up Segment to be enriched with Optimizely Feature Experimentation data.

📘

Note

This page has up-to-date information for Optimizely Feature Experimentation integration with Segment. The Segment-hosted docs update less frequently.

Get started

The first step is to make sure Optimizely Feature Experimentation 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.

WebMobileServer
📱 Device-modeYes
☁️ Cloud-modeYesYes

Segment’s Optimizely Feature Experimentation (previously Optimizely Full Stack) destination supports the following Optimizely Experimentation products:

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

Optimizely Web Experimentation

Optimizely Full Stack (JavaScript)

Implementation prerequisite

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

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

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

Server Side

Get Started

  1. In your Segment source dashboard, enable the “Optimizely Full Stack” destination (not the “Optimizely Web” destination).
  2. Include your Optimizely Feature Experimentation project’s projectId and datafile URL in your Segment settings.
  3. Create a native Optimizely Feature Experimentation instance in your server environment so you can access Optimizely Feature Experimentation methods like Is Feature Enabled, etc.
  4. Finally, define any metrics and attributes in your Optimizely Feature Experimentation dashboard, and to associate metrics with the appropriate Optimizely Feature Experimentation 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 Feature Experimentation attributes.

📘

Note

If you are using Full Stack Legacy SDKs from before 2019: 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.

For more information, see the Event API documentation. Set up does not require maintaining the attributes of a user as long as the user id stays the same between decision-based methods, such as the Is Feature Enabled method, and Segment track calls to have Optimizely Feature Experimentation metrics populated in the Optimizely Feature Experimentation results page. If you would like to segment your Optimizely Feature Experimentation results by user attribute, then make sure the attributes passed in for the decision-based 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 the documentation, Count conversions.

Example Optimizely Feature Experimentation implementation

See the following example code for instructions on integrating the JavaScript SDK with your Segment analytics.

//Node server-side example

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

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

const segmentDecision = (decisionObject) => {
  const 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") {
    const info = decisionObject.decisionInfo;
    const featureKeyString = info.featureKey;
    const enabled = info.featureEnabled;
    const 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") {
      const experimentKeyString =info.sourceInfo.experimentKey;
      const experimentVarString = info.sourceInfo.variationKey;
      analytics.track('Experiment Viewed', {
        'experiment_name': experimentKeyString,
        'variation_name': experimentVarString
      })
    }
  }
}

const listenerId = optimizely.notificationCenter.addNotificationListener(
  optimizelyEnums.NOTIFICATION_TYPES.DECISION,
  segmentDecision,
);

Track

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

  • If the Segment event name matches exactly the name of an active experiment metric set up in the Optimizely Feature Experimentation 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 Feature Experimentation eventName.
  • Segment track event properties to Optimizely Feature Experimentation eventTags.
  • Segment track event context.traits to Optimizely Feature Experimentation 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 Feature Experimentation, which includes any Event Tag outside of revenue or value, will not be displayed on the Optimizely Feature Experimentation 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

Get Started

  • In your Segment source dashboard, enable the “Optimizely Full Stack” destination (not the “Optimizely Web” destination).
  • Include the latest version of Optimizely Feature Experimentation 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 Feature Experimentation dashboard and to associate metrics with the appropriate Optimizely Feature Experimentation 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 Feature Experimentation via cloud-mode, Segment will map track events to Optimizely track events on our servers and deliver the data to your Optimizely Feature Experimentation 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.

For more details on how events are attributed on the Optimizely Feature Experimentation results page, refer to the documentation, Count conversions.

Example Optimizely Feature Experimentation 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 a notification 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, ?> attributes, Variation variation, LogEvent event) {

    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 Feature Experimentation eventName.
  • Segment track event properties to Optimizely Feature Experimentation eventTags.
  • Segment track event context.traits to Optimizely Feature Experimentation 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 Feature Experimentation. 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

Get Started

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

When implementing Optimizely Feature Experimentation via cloud-mode, Segment will map track events to Optimizely track events on our servers and deliver the data to your Optimizely Feature Experimentation 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.

For more details on how events are attributed on the Optimizely results page, see the documentation, Count conversions.

Example Optimizely Feature Experimentation 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 a notification 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 Feature Experimentation track event:

  • If the Segment event name matches exactly the name of an active experiment metric set up in the Optimizely Feature Experimentation 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 Feature Experimentation eventName.
  • Segment track event properties to Optimizely Feature Experimentation 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 Feature Experimentation attributes. The attributes are sent downstream to Optimizely upon invocation of the next Segment track event.

Personas

Follow the instructions on Using Segment Personas and Optimizely Full Stack for Omnichannel Experiments.

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 Feature Experimentation and provide it as the value of the Access Token setting.

Supported Sources and Connection Modes

The first step is to make sure Optimizely Feature Experimentation supports the source type and connection mode you have chosen to implement. You can learn more about what dictates the connection modes we support refer to the Segment documentation.

WebMobileServer
📱 Device-modeYes
☁️ Cloud-modeYesYes

Segment offers an optional Device-based Connection Mode for Mobile data going to Optimizely Feature Experimentation so that you can use Optimizely Feature Experimentation 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 Expiration

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, 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 Feature Experimentation does not alias known and unknown users. By default, Segment will only send the anonymousId to Optimizely Feature Experimentation. Enable this to only send the userId to Optimizely Feature Experimentation. 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 are 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:

let myVariable = try? optimizely.getFeatureVariableBoolean(featureKey: "", variableKey: "", userId: "")

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 Feature Experimentation client using v3.2.2 of Optimizely’s SDK. The default Optimizely Feature Experimentation 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 version 3.0. You can find more information on how migrating from Optimizely 2.x to 3.x will affect your experiment tracking in Optimizely Feature Experimentation'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

Add Optimizely Feature Experimentation to the integrations object

To add Optimizely Feature Experimentation 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