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

# Webhooks

> Create webhook endpoints, verify signatures with constructEvent and query and replay deliveries with the SDK.

`routa.webhooks` manages webhook endpoints and verifies the deliveries you receive. For the concepts, see [Webhooks overview](https://docs.routa.chat/en/webhooks/overview.md).

## Create an endpoint

Register an HTTPS URL and store the signing secret. It is returned **only once**, on creation (and again on rotation).

```ts theme={null}
const webhook = await routa.webhooks.create({
  url: 'https://example.com/webhooks/routa',
  subscribedTypes: ['message.*'],
})

console.log(webhook.id, webhook.secret) // store the secret safely
```

## Manage endpoints

| Method | Description |
| - | - |
| `create({ url, subscribedTypes })` | Creates the endpoint and returns the `secret`. |
| `list()` | Lists the endpoints of the project (5 at most). Returns a `Page`. |
| `retrieve(id)` | Retrieves an endpoint. |
| `update(id, { subscribedTypes })` | Replaces the subscribed types. |
| `rotateSecret(id)` | Generates a new secret. The previous one stays valid for 24 hours. |
| `disable(id)` | Pauses deliveries. |
| `enable(id)` | Re-enables the endpoint and replays every exhausted delivery. Returns `replayedCount`. |

```ts theme={null}
const { secret } = await routa.webhooks.rotateSecret(webhook.id)
const result = await routa.webhooks.enable(webhook.id)
console.log(result.replayedCount)
```

## Verify a delivery with `constructEvent`

Routa signs each delivery in the `Routa-Signature` header. `constructEvent` verifies the signature and returns a typed event. It **makes no network calls**.

Pass the **raw body** exactly as received. Parsing and serializing it again changes the bytes, and the signature no longer matches.

```ts theme={null}
import { Routa, RoutaSignatureVerificationError } from '@routa-chat/sdk'

const routa = new Routa({ apiKey: process.env['ROUTA_API_KEY']! })
const signingSecret = process.env['ROUTA_WEBHOOK_SECRET']! // the `secret` from webhooks.create()

// Works with any framework that hands you a Fetch API `Request`.
export async function handleWebhook(request: Request): Promise<Response> {
  const rawBody = await request.text()

  try {
    const event = await routa.webhooks.constructEvent(
      rawBody,
      request.headers.get('routa-signature'),
      signingSecret
    )

    switch (event.type) {
      case 'message.delivered':
        console.log('delivered', event.data)
        break
      case 'message.failed':
        console.log('failed', event.data)
        break
    }

    return new Response(null, { status: 200 })
  } catch (error) {
    if (error instanceof RoutaSignatureVerificationError) {
      return new Response('Invalid signature', { status: 400 })
    }
    throw error
  }
}
```

`constructEvent` accepts the body as a `string` or `Uint8Array` and rejects signatures that are missing, malformed, invalid or with a timestamp outside the 5-minute tolerance, throwing `RoutaSignatureVerificationError`.

### Secret rotation

During a rotation, pass both secrets to accept either one:

```ts theme={null}
const event = await routa.webhooks.constructEvent(rawBody, header, [newSecret, oldSecret])
```

### Event types

From 0.3.0, the SDK knows 17 event types:

| Group | Types |
| - | - |
| Messages | `message.accepted`, `message.sent`, `message.delivered`, `message.read`, `message.failed`, `message.received` |
| Channels | `channel.status_changed` |
| Templates | `template.submitted`, `template.pending`, `template.approved`, `template.rejected`, `template.paused`, `template.disabled`, `template.failed`, `template.category_changed`, `template.updated`, `template.deleted` |

See the content of `data` for each type in [Event types](https://docs.routa.chat/en/webhooks/event-types.md). `data` is the API's own JSON, in *snake\_case*: a `message.*` event of a template send carries `content.header_parameter` and `content.button_parameters`, and a `template.*` event carries the examples in `variables[].example`.

A type introduced after your installed version is still parsed: it arrives as a generic event, with `type` typed as `string` and `data` as `unknown`, and it is safe to ignore.

> [!NOTE]
>
> Because the last member of the `RoutaEvent` union has `type: string`, a `switch (event.type)` alone does not narrow the other fields. Check `'id' in event` first to get the full envelope.

### The event envelope

Every known event has these fields, in *camelCase*:

| Field | Type | Description |
| - | - | - |
| `id` | `EventId` | Event ID. |
| `type` | `EventType` | Event type. |
| `apiVersion`, `schemaVersion` | `string`, `number` | Contract versions. |
| `projectId` | `string` | Project of the event. |
| `externalRef` | `string \| null` | The `external_ref` of the project, or `null` when it has none. Available from 0.3.0. |
| `sequence` | `number` | Order of the event. |
| `occurredAt`, `recordedAt` | `string` | ISO 8601. |
| `data` | `unknown` | Body of the event. Interpret it by the value of `type`. |

A [partner](https://docs.routa.chat/en/sdk/partner.md#receive-the-events-of-every-customer) webhook endpoint receives the events of every project in the organization. Use `projectId` and `externalRef` to tell which customer each event belongs to. To verify the signature of those deliveries, use `partner.webhook.constructEvent()`, which does the same as `routa.webhooks.constructEvent()`.

### Handle every type

With 17 types, it pays to handle the groups by prefix and ignore what you do not use:

```ts theme={null}
const event = await routa.webhooks.constructEvent(rawBody, header, signingSecret)

if ('id' in event) {
  switch (event.type) {
    case 'template.updated':
    case 'template.deleted':
      // The template was edited or deleted in the dashboard. `data` is the full template.
      break
    case 'template.failed':
      // Routa could not send the template. `data` is the template, with `failure_code`.
      break
    default:
      // Any other type, including the ones that do not exist yet: safe to ignore.
      break
  }
}
```

> [!NOTE]
>
> If your code uses an exhaustive `switch` with a `never` check over `EventType`, it stops compiling on 0.3.0 until it handles the four new types. See [Upgrade to 0.3.0](https://docs.routa.chat/en/sdk/upgrading.md).

## Deliveries and replay

`routa.webhooks.deliveries` queries the deliveries of an endpoint and replays the exhausted ones. See [Retries and replay](https://docs.routa.chat/en/webhooks/retries-and-replay.md).

```ts theme={null}
// Deliveries that ran out of attempts
for await (const delivery of routa.webhooks.deliveries.list(webhook.id, { state: 'exhausted' })) {
  console.log(delivery.id, delivery.eventType, delivery.lastResponseStatus)
}

// Replay one delivery
await routa.webhooks.deliveries.replay(webhook.id, deliveryId)

// Replay every exhausted delivery of the endpoint
const { replayedCount } = await routa.webhooks.deliveries.replay(webhook.id)
```

## Missed events

If your endpoint was down, `routa.events.list()` returns what you did not receive. See [Reconcile events](https://docs.routa.chat/en/webhooks/reconciliation.md).


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