> ## Documentation Index
> Fetch the complete documentation index at: https://getlago.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Segment

> Send usage tracked in Segment to Lago with a destination function that posts events to /api/v2/events using external_contract_id.

The Segment integration forwards product usage tracked in Segment to Lago as billable events. Use it when Segment already captures the actions you bill on and you want Lago to rate them against a contract.

## Prerequisites

**In Lago:**

1. Create a Lago organization to manage your billing and invoicing.
2. Create a [billable metric](https://getlago.com/docs/v2/guide/billable-metrics/create-billable-metrics.md) to track the usage of your customers.
3. Create a [metered product](https://getlago.com/docs/v2/guide/product-catalog/metered-products.md) on that metric, price it with a [rate card](https://getlago.com/docs/v2/guide/rate-cards/overview.md), and add it to a [plan](https://getlago.com/docs/v2/guide/plans/overview.md).
4. Create a [customer](https://getlago.com/docs/v2/guide/customers/customer-management.md) and a [contract](https://getlago.com/docs/v2/guide/contracts/overview.md) for that customer.

**In Segment:**

1. Create a Segment account.
2. Create a data source (ideally, product usage of your customer).

## Send usage from Segment to Lago

### Create a function

Create a custom **Function** in Segment:

1. Navigate to the **Catalog** in Segment.
2. Click the **Functions** tab to access the custom Functions feature.
3. Choose to create your first function and follow the prompts to set it up.

![Segment catalog with the Functions tab open](https://mintcdn.com/lago-docs/aaVDsanqVM_V30mw/integrations/usage/images/segment-catalog-1a7de549eb06d94a6a8ce92565e957a8.png?fit=max\&auto=format\&n=aaVDsanqVM_V30mw\&q=85\&s=ff517969f241be63547b33ea49004bbe)

Segment Functions

### Use the destination function

Select the **Destination function**, as you want to send data from Segment to Lago.

![Segment function type picker with Destination function selected](https://mintcdn.com/lago-docs/aaVDsanqVM_V30mw/integrations/usage/images/destination-function-segment-6131770a6f0e5b7c8e7bf694ca6339b3.png?fit=max\&auto=format\&n=aaVDsanqVM_V30mw\&q=85\&s=d374f48ed23590453a0e515f59ee209f)

Destinations function

### Post requests to Lago events

Replace the pre-written code in the editor with the function below. It catches a **Track** event from Segment, builds a Lago event body and posts it to [`POST /api/v2/events`](https://getlago.com/docs/v2/api-reference/events/create). Each event targets a contract through `external_contract_id`.

```javascript theme={"dark"}
// Runs every time a Track call is made on Segment
async function onTrack(event, settings) {

  // Lago events endpoint
  const endpoint = 'https://api.getlago.com/api/v2/events';

  // Event body following the Lago events schema
  const body = {
    event: {
      transaction_id: event.messageId,
      // map this to the external_id of the Lago contract being metered
      external_contract_id: event.properties.contract_id,
      code: event.event,
      timestamp: Math.floor(new Date(event.timestamp).getTime() / 1000),
      properties: {
        invoice_id: event.properties.invoice_id
      }
    }
  };

  // Post event
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${settings.api}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  });

  return response.json();
}
```

> [!NOTE]
>
> `transaction_id` and `code` are required. `code` must match the code of a billable metric. `external_contract_id` must match the `external_id` of the contract you bill. The example reads it from a `contract_id` property on the Segment event. Map it from wherever your tracking plan stores it. For EU-hosted organizations, use `https://api.eu.getlago.com/api/v2/events`.

> [!NOTE]
>
> This function can be adapted to Identify, Group or Page events. Refer to [Segment's documentation](https://segment.com/docs/connections/functions/destination-functions/) for all available actions. The `properties` object depends on your billable metric. Add or remove properties, and add conditions to send only specific events to Lago.

### Use the test mode editor

Use a sample event in the **Test** panel to preview the data fetched from a Segment event and debug the function before you deploy it.

### Hide sensitive data

The function reads the **API key** from a setting instead of hard-coding it. Store it as a sensitive variable.

To create **Settings** variables:

1. Go to the **Settings** tab.
2. **Add** a new Setting.
3. Define a **Name** and a **Label** for this Setting.
4. Define it as **Required** or **Optional**.
5. Mark it as **Sensitive**.

![Segment function Settings tab with a sensitive API key variable](https://mintcdn.com/lago-docs/aaVDsanqVM_V30mw/integrations/usage/images/segment-settings-variable-c19b5f3de23eec11ffe475e8272dc5ff.png?fit=max\&auto=format\&n=aaVDsanqVM_V30mw\&q=85\&s=2326eb0d7eb514d91a0450674b69723b)

Hide sensitive data with settings variables

### Send usage events to Lago

Run the function in Segment to send a test event to Lago. Check it in the events list or with [`GET /api/v2/events`](https://getlago.com/docs/v2/api-reference/events/list). Once the setup is finalized in Segment, the function triggers automatically on your defined behavior.

## Segment to Lago demo video

> [!NOTE]
>
> This video was recorded with the legacy v1 events payload. Its Segment setup steps still apply. Use the V2 code above for the endpoint and the contract identifier.

[Segment to Lago demo video](https://www.youtube.com/embed/lyJmdh47JTE)

> [card] [Ingest usage](https://getlago.com/docs/v2/guide/events/ingesting-usage.md)
>
> How events target a contract.

> [card] [Ingest an event](https://getlago.com/docs/v2/api-reference/events/create.md)
>
> `POST /api/v2/events` reference.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.