# Segment

Enabling the Segment integration for Statsig allows Statsig to pull in your Segment events. This integration lets you run your experiment analysis on Statsig with all of your existing events from Segment without requiring any additional logging.

When Statsig receives events from Segment, Statsig displays and aggregates them in the [Metrics](https://docs.statsig.com/metrics/introduction) tab in the Statsig console. Statsig automatically includes these events in your [Pulse](https://docs.statsig.com/experiments/interpreting-results/read-results) results for A/B tests with Statsig's feature gates and all your [Experiment](https://docs.statsig.com/experiments/monitor) results.

### Supported Segment event types

* [Track](https://segment.com/docs/connections/spec/track/)
* [Page](https://segment.com/docs/connections/spec/page/)
* [Group](https://segment.com/docs/connections/spec/group/)
* [Screen](https://segment.com/docs/connections/spec/screen/)
* [Identify\*](https://segment.com/docs/connections/spec/identify/)

{% callout type="info" %}
Statsig supports Identify calls only for syncing Segment Engage Audiences with Statsig Segments.
{% /callout %}

### Benefits of using the Segment integration

The Segment integration has several benefits over other methods of event ingestion:

* Customers ingesting data with Segment can quickly populate Statsig with metrics and can typically get started within a day.
  * Customers only need to use Statsig's assignment SDKs (gate/experiment allocation), which simplifies code and engineering workflows.
  * You can do additional logging through the [event logging SDKs](https://docs.statsig.com/guides/logging-events#logging-events-via-sdks), but it requires additional code orchestration and a collection window.
* With [event filtering](https://docs.statsig.com/integrations/event_filtering) you can control which events are ingested and make billing more predictable.
* If you have [Segment Replay](https://segment.com/docs/guides/what-is-replay/), you can forward up to 7 days of historical events to Statsig for analysis.

## Configuring inbound events into Statsig

{% callout type="note" %}
Ingestion with this integration is available only for Statsig Cloud. For Warehouse Native, create a metrics source that references this data in your warehouse.
{% /callout %}

To send events collected from Segment into Statsig, you must configure the Statsig Destination within your Segment account:

### Using OAuth

The easiest way to connect Statsig to Segment is through OAuth.

1. To get started, within the Statsig Console, go to **project settings → integrations → Segment → Enable**

2. Click “Configure Segment OAuth”

   {% figure %}
   ![Statsig integration settings showing Segment OAuth button](https://docs.statsig.com/images/integrations/data-connectors/segment/262495276-2fa7d870-0f02-44cf-aa29-9f04b0b12220.png)
   {% /figure %}

3. Select the workspace and source that sends data to Statsig. Click “Allow”:

   {% figure %}
   ![Segment OAuth consent screen selecting workspace and source](https://docs.statsig.com/images/integrations/data-connectors/segment/262495274-71e8dbf3-590f-44bf-90bd-5723dd3c60ed.png)
   {% /figure %}

4. After you enable the integration, you can configure event filtering and map additional identifiers. Mapping additional identifiers is useful for device-level identifiers and `anonymousIds` generated from Segment.
   Statsig recommends creating a custom ID called `segmentAnonymousId` and mapping the `anonymousId` from Segment to it.
   {% figure %}
   ![Statsig Segment integration panel with identifier mapping options](https://docs.statsig.com/images/integrations/data-connectors/segment/279802493-6956e8f7-28f1-4ac9-88d1-96710240373b.png)
   {% /figure %}

### Manual configuration

If you're unable to connect to Segment through OAuth, you can manually connect Statsig to Segment by configuring the following:

1. Within the [Segment App](https://app.segment.com), navigate to your Destinations, and select "**Add Destination**"

2. Search for “**Statsig**” and select the destination

   {% figure %}
   ![Segment destination catalog listing Statsig](https://docs.statsig.com/images/integrations/data-connectors/segment/262495271-68b0959b-b1d8-4041-a413-e0b2c3802377.png)
   {% /figure %}

3. Select "Statsig" from the list of available integrations, and then select **sources** that send data to Statsig.
   {% figure %}
   ![Segment destination setup selecting sources](https://docs.statsig.com/images/integrations/data-connectors/segment/262495270-832e8d93-1896-4c24-bf42-c56f627eecbc.png)
   {% /figure %}

4. You must provide a Statsig Server SDK key. You can copy an existing server key or create a new one from the [Statsig console settings](https://console.statsig.com/api_keys).
   * Create or copy a server SDK key

     {% figure %}
     ![Statsig API keys page showing server key](https://docs.statsig.com/images/integrations/data-connectors/segment/262495269-88b47af6-7313-47e9-a767-e1eb12b4e47b.png)
     {% /figure %}

     {% figure %}
     ![Segment destination configuration entering Statsig server key](https://docs.statsig.com/images/integrations/data-connectors/segment/262504950-c5b21cc0-5b51-4a55-997a-74b8a45b2807.png)
     {% /figure %}

   * Put your Server Secret Key in the “API Key” field in the Statsig Destination

     {% figure %}
     ![Segment destination API key input](https://docs.statsig.com/images/integrations/data-connectors/segment/262506044-77bef6e4-c79d-47b2-94cc-3f6b3dc06489.png)
     {% /figure %}

5. To set up mappings, you must enable the Segment Integration in Statsig. Go to the Statsig Console, then Project Settings, then the Integrations tab, then Segment, and click **Enable**:

   {% figure %}
   ![Statsig Segment integration enable toggle](https://docs.statsig.com/images/integrations/data-connectors/segment/262506930-12225ae2-a12e-4b0d-9efc-34c03a840f9f.png)
   {% /figure %}

   * After you enable the integration, you can configure event filtering and map additional identifiers. Mapping additional identifiers is useful for device-level identifiers and `anonymousIds` generated from Segment.
     {% figure %}
     ![Statsig identifier mapping form](https://docs.statsig.com/images/integrations/data-connectors/segment/279802493-6956e8f7-28f1-4ac9-88d1-96710240373b.png)
     {% /figure %}

6. Verify that Statsig is receiving events using the [Segment Event Tester](https://segment.com/docs/connections/test-connections/).
   * In the event tester, send a test event to verify any filtering and mapping you've set up:

     {% figure %}
     ![Segment integration panel showing outgoing toggle](https://docs.statsig.com/images/integrations/data-connectors/segment/262495256-5097e8a0-ca4f-4e1a-b2b6-3337d6fe7bff.png)
     {% /figure %}

   * In the your [Statsig Console Events Explorer](https://console.statsig.com/metrics/events), click on the test event in the log stream and verify the event:

     {% figure %}
     ![Segment destination configuration for outgoing data](https://docs.statsig.com/images/integrations/data-connectors/segment/262501895-001d1179-510a-4171-9ab9-f14544c94374.png)
     {% /figure %}

   * In this example, the mapping connects the `anonymousId` to Statsig’s `segmentAnonymousId`. Statsig infers the User ID from the Segment `userID` field.

     {% figure %}
     ![Statsig integration for Segment Engage audience mapping](https://docs.statsig.com/images/integrations/data-connectors/segment/279802493-6956e8f7-28f1-4ac9-88d1-96710240373b.png)
     {% /figure %}

7. As your Segment events flow into Statsig, you see a live **Log Stream** in the [Metrics](https://docs.statsig.com/metrics/introduction) tab in the Statsig console. You can click one of these events to see the details logged as part of the event.
   {% figure %}
   ![Log details panel showing Segment event payload fields and metadata](https://docs.statsig.com/images/integrations/data-connectors/segment/150830169-17564060-816b-4c5c-ade9-10bf6274265a.png)
   {% /figure %}

## Working with users

Statsig joins incoming user identifiers to whichever [unit of randomization](https://docs.statsig.com/experiments/overview#choosing-the-right-randomization-unit) you choose. This flexibility lets you test on known (userID) and unknown (anonymousID) traffic, as well as any custom identifiers your team uses (deviceID, companyID, vehicleID).

### User IDs and custom IDs

Statsig automatically detects the `event` and `userId` fields logged through your Segment events (refer to [`track`](https://segment.com/docs/connections/spec/track/) for an example). If you're running an experiment with the userId as your unit type, this `userID` should match the user identifier that you log with the Statsig SDK.

If you're using a [custom ID](https://docs.statsig.com/guides/experiment-on-custom-id-types) as the unit type for your experiment, you can provide this identifier using the key `statsigCustomIDs` as part of the Segment `properties` field as shown below.

```bash title="JSON Body"
{
  ...
  properties: {
    "statsigCustomIDs": [ "companyID", "<this_company_id>"]
  }
}
```

The `statsigCustomIDs` field in properties should be an array. In this array, the even index is the name of the user ID type, and the odd index is the value of the previous element. After you create this custom ID type on Statsig (under **ID Type Settings** in your [Project Settings](https://console.statsig.com/settings)), Statsig automatically recognizes these custom identifiers to compute your experiment results.

### Anonymous users

#### Mapping anonymous users

The Segment integration also allows the mapping of top-level fields to custom IDs you define in Statsig. To map fields, visit the Segment panel on the Statsig Integrations page and look for the "Map Identifier" section. Here you can choose fields to map to a [Custom ID](https://docs.statsig.com/guides/experiment-on-custom-id-types).
Field mapping is useful for working with the [Segment anonymous ID](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/identity/#anonymous-ids), which Segment passes as an event field `anonymousId`. By defining a custom ID called `segmentAnonymousId`, Statsig can map your anonymous Segment traffic to your metric data.

{% callout type="warning" %}
Values passed in `properties.statsigCustomIDs` take precedence over mapped identifiers below.
{% /callout %}

![Segment integration card with Map Identifiers form mapping anonymousId to custom ID](https://docs.statsig.com/images/integrations/data-connectors/segment/279802493-6956e8f7-28f1-4ac9-88d1-96710240373b.png)

#### Experimenting on anonymous traffic

For example, if you're running experiments on anonymous users, you can use Segment's `anonymousId` as the unit of randomization. First, [add a new customer identifier to Statsig](https://docs.statsig.com/guides/experiment-on-custom-id-types#step-1---add-companyid-as-a-new-id-type-in-your-project-settings). In this example, the new custom ID is `segmentAnonymousId`. Then, when [initializing](https://docs.statsig.com/client/javascript-sdk) the Statsig SDK, pass the Segment `anonymousId` to Statsig as a custom ID if it's available. For example, your Statsig initialization may look like this:

```jsx
import { StatsigClient } from '@statsig/js-client';

await Statsig.initialize(
  "client-sdk-key",
  
);
const client = new StatsigClient(sdkKey,
  {
    userID: "some_user_id",
    customIDs: {
      segmentAnonymousId: analytics.user().anonymousId()
    }
  },
  { environment: { tier: "production" } }
);

```

You can access Segment's `anonymousId` using `analytics.user().anonymousId()` as [outlined in the Segment docs here](https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/identity/).

{% callout type="note" %}
The Segment SDK may initialize after the Statsig SDK, and the `anonymousId` may not be available in that scenario. Check the timing in your specific implementation. If you're using vanilla JavaScript, wait for the `anonymousId` from the Segment SDK after initialization, then call the `updateUser()` method on the Statsig SDK to update this ID.
{% /callout %}

#### Example mapping flow

Refer to the following diagram for an overview of mapping `anonymousIds` in Segment to a custom ID representing anonymous users in Statsig:

{% figure %}
![Identifier mapping flowchart](https://docs.statsig.com/images/integrations/data-connectors/segment/283278011-3c22e6e8-ab36-4844-aee2-b6630ecda4de.png)
{% /figure %}

1. Initialize the Statsig SDK with your [Statsig User](https://docs.statsig.com/sdks/user), which contains an optional `userID` value and a `customID` that you've created in the Statsig UI - `segmentAnonymousId` in this example.
2. As you orchestrate features and experiments, Statsig associates this user to a variant using the unit of randomization chosen. For anonymous users, Statsig uses `segmentAnonymousId`.
3. Your existing Segment implementation tracks user traffic and associates anonymous users to the top-level field `anonymousId`.
4. Statsig maps this `anonymousId` (to `segmentAnonymousId`), properly associating the identifier used in experiment exposures to the same identifier used to track user actions.

### Syncing Statsig Segment ID lists with Segment Engage Audiences

Using [Segment Engage Audiences](https://segment.com/docs/engage/audiences/), you can maintain a list of users for targeting using [Statsig Feature Gates](https://docs.statsig.com/feature-flags/overview). To configure this:

1. Create a [Statsig ID List Segment](https://docs.statsig.com/segments/create-new) on the Statsig Console.
2. Follow the [Segment guide for Audiences](https://segment.com/docs/engage/audiences/) to create a new Audience and choose `Statsig` as a Destination. The `audience_key` must match the ID of the `Statsig ID List Segment` created.

After you complete these steps, Statsig syncs your Segment Audience, and you can target those users for features you develop or experiments you run.

### Custom properties

Passing [custom properties to a Statsig User](https://docs.statsig.com/sdks/user#user-attributes) (refer to the `custom` field) enables targeting on specific cohorts of users in feature gates and experimentation. Custom user properties also let you filter results to specific populations (for example: android/iOS, isVIP) when [reading pulse results](https://docs.statsig.com/experiments/interpreting-results/custom-queries#running-a-custom-query).

If you're using custom fields to [target users](https://docs.statsig.com/feature-flags/conditions#custom) in your feature gates, provide these properties through Segment. Use the key `statsigCustom` as part of the Segment `properties` field, as an array of key-value pairs: `[key1, value1, key2, value2, ...]`. For example:

```bash title="JSON Body"
{
  ...
  properties: {
    "statsigCustom": [ "isVIP", "true", "marketing_campaign", "abx343", ...]
  }
}
```

## Configuring outbound events to Segment

To export your Statsig events to Segment,

1. In your Segment app, add a new source → search for Statsig → click **Next**

{% figure %}
![Segment outbound configuration selecting Statsig destination](https://docs.statsig.com/images/integrations/data-connectors/segment/263066497-1856270d-adb9-4ca7-9349-1b4b393b1aa2.png)
{% /figure %}

2. Name your source → Create Source → click **Done**:

{% figure %}
![Segment workspace auth prompt for outbound integration](https://docs.statsig.com/images/integrations/data-connectors/segment/263066506-cbe5beca-5971-4baf-ae41-571bd7c1ae52.png)
{% /figure %}

3. Locate your **Write Key** and copy it.
4. Log into the Statsig console and navigate to the [**Integrations**](https://console.statsig.com/integrations) page.
5. Click on the **Segment** card and switch to the **Outbound** tab, paste the **Write Key** into the **API Key** text box shown below, and click **Enable**.

{% figure %}
![Segment outbound integration configuration interface](https://docs.statsig.com/images/integrations/data-connectors/segment/150827399-333d9064-de1c-4f4e-bc33-51a46a83531d.png)
{% /figure %}

### Outbound event schema

Statsig exports log events and exposure events to Segment as `track` events:

```
{
    type: 'track',
    userId: event.userID,
    timestamp: Number(event.timestamp),
    event: event.eventName,
    context: {
      user: event.user,
      value: event.value,
      metadata: event.metadata,
      library: {
        name: 'statsig',
        version: '1.0',
      },
      stableID: event.statsigMetadata.stableID // stableID, if you are relying on that for anonymous users
    },
    properties: {
      value: event.value,
      metadata: event.metadata,
    },
  };
}
```

Config Change events follow this schema:

```
{
  userId: statsigUserID,
  timestamp: Date.now(),
  event: 'statsig::config_change',
  context: {
    library: {
      name: 'statsig',
      version: '1.0',
    },
  },
  properties: {
    author: author,
    configName: configName,
    description: changeDescription,
    environment: environment,
  },
},
```

## Environments

By default, Statsig treats all events as "production" events, but you can differentiate your event traffic by specifying the environment the events are coming from. This prevents non-production data from appearing in your production metrics.

To include the environment tier, add it to the properties object of your event.
The required format is below:

```json
{
  ...
  "properties": {
   "statsigEnvironment": {
        "tier": "staging"
    }
  }
}
```

To learn more about environments, refer to [Using Environment](https://docs.statsig.com/guides/using-environments).

## Working with Segment metrics in the Statsig UI

Statsig pipes Segment events in, and they're accessible in the metrics console like any other event. You can also use these metrics as monitoring metrics in your feature gates and experiments. Using them this way lets you combine your existing Segment metric collection with Statsig's experimentation platform.

{% callout type="note" %}
Statsig prepends `segment::` to Segment events so you can easily distinguish them from other sources
{% /callout %}

{% figure %}
![Segment destination configuration for first exposures](https://docs.statsig.com/images/integrations/data-connectors/segment/263068916-a7bb398b-dd5f-4a0c-9c72-924f384a54b7.png)
{% /figure %}

These metrics appear in pulse results among other monitoring metrics:

{% figure %}
![Segment HTTP endpoint settings](https://docs.statsig.com/images/integrations/data-connectors/segment/263068905-12265a7e-e13a-4350-8bda-76ecfb3a805c.png)
{% /figure %}

## Filtering events

You can customize which events you send and receive through Segment using [Event Filtering](https://docs.statsig.com/integrations/event_filtering).
