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

# Lago

> Send Narev Cloud LLM usage events to Lago and sync customers so you can bill end users for AI consumption with subscriptions and metered pricing.

# Lago billing platform integration

Use this guide after your framework-level integration is complete.

This page covers Lago-specific setup:

* Create the `@ai-billing/lago` destination.
* Map usage events to Lago customers.
* Sync user identity with `external_id`.

For the server middleware setup, use [Node.js billing integration](/docs/platform/billing/integrations/frameworks/nodejs).

## Metering strategy

Lago integrations with Narev use **nanos metering** only: one billable metric aggregates `cost_nanos` from each event. Narev resolves the dollar cost at request time, so you do **not** copy token rates into Lago plans.

The removed Narev Cloud Connect flow provisioned a metric named `LLM Usage Nanos` with code `llm_usage_nanos`, aggregating the `cost_nanos` field. You can create the same metric manually or use any code. Keep `meterCode` in your destination config aligned with it.

<Note>
  Narev Cloud no longer hosts a Connect dashboard for Lago. Credentials and billable metrics live in your Lago workspace and application environment variables. Itemized per-model product sync was never supported for Lago.
</Note>

## Before you start

Create a billable metric in the [Lago Dashboard](https://app.getlago.com) with code `llm_usage`. The `meterCode` in your destination config must match that code.

## Install Lago dependencies

```bash theme={null}
pnpm add @ai-billing/lago
```

## Configure environment variables

Set these on your server:

```bash theme={null}
LAGO_API_KEY=****
# Optional for self-hosted Lago
LAGO_API_URL=https://api.getlago.com
```

Use a sandbox or test organization until your metering flow is verified.

## Create Lago billing destinations

Create `lib/ai/destinations.ts`:

```ts lib/ai/destinations.ts theme={null}
import { createLagoDestination } from '@ai-billing/lago';

export function getBillingDestinations() {
  const lagoApiKey = process.env.LAGO_API_KEY;

  if (!lagoApiKey) return [];

  return [
    createLagoDestination({
      apiKey: lagoApiKey,
      apiUrl: process.env.LAGO_API_URL,
      meterCode: 'llm_usage',
      externalCustomerIdKey: 'userId',
    }),
  ];
}
```

The key mapping is `externalCustomerIdKey: 'userId'`. Your billing tags must include `userId`.

## Sync Lago customers when users sign up

Create `lib/lago-client.ts`:

```ts lib/lago-client.ts theme={null}
export async function createLagoCustomer(email: string, userId: string) {
  const apiKey = process.env.LAGO_API_KEY;
  const apiUrl = process.env.LAGO_API_URL ?? 'https://api.getlago.com';

  if (!apiKey) return;

  try {
    const response = await fetch(`${apiUrl}/api/v1/customers`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        customer: {
          external_id: userId,
          email,
        },
      }),
    });

    if (!response.ok) {
      throw new Error(`Lago API returned ${response.status}`);
    }
  } catch (error) {
    console.error('[ai-billing] Failed to create Lago customer:', error);
  }
}
```

Call this when a user signs up:

```ts theme={null}
if (newUser) {
  await createLagoCustomer(validatedData.email, newUser.id);
}
```

The Lago customer API upserts on `external_id`, so repeated calls with the same `userId` update the existing record.

## Required tag contract

In your generation routes, include:

```ts theme={null}
providerOptions: {
  'ai-billing-tags': {
    userId: session.user.id,
    modelId: chatModel,
    chatId: id,
  },
}
```

Contract requirements:

* `userId` in `ai-billing-tags` must match the Lago customer `external_id`.
* Each user should have one Lago customer record.
* If `userId` is missing, the destination skips the event to avoid ingesting anonymous usage.

<Note>
  The Lago destination sends `cost_nanos` and `currency` in the event properties. If your provider does not return pricing natively, attach a price resolver (for example, Narev) in your framework middleware. See [@ai-billing/lago reference](/docs/sdk/ai-billing/reference/lago/index).
</Note>

## Verify Lago metering

1. Register a new user and confirm a Lago customer exists with `external_id = userId`.
2. Trigger a model call and confirm an event with code `llm_usage` appears in Lago.
3. Validate properties contain `cost_nanos`, `currency`, `userId`, and your route context tags.
4. Confirm `LAGO_API_URL` points at the Lago instance you are checking.

## Common issues

### Events appear but don't map to customers

* Confirm `userId` exists in `ai-billing-tags`.
* Confirm destination uses `externalCustomerIdKey: 'userId'`.
* Confirm customer creation uses `external_id = userId`.

### No events arrive in Lago

* Confirm `LAGO_API_KEY` is present at runtime.
* Confirm the billable metric code matches your Lago configuration.
* Confirm framework routes call the billing-wrapped model helper.
* Confirm each billing event includes a defined `cost` (attach a price resolver if needed).

### Events are skipped silently

* Lago skips events when no customer identity tag is found. Confirm `userId` is set on every generation call.
