> ## 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.

# Messages

> Send, retrieve, list and mark messages as read with routa.messages.

`routa.messages` covers the message lifecycle. Each method maps to a [REST API](https://docs.routa.chat/en/api-reference/endpoint/messages/send.md) endpoint.

## `send`

Sends text or an approved template. Returns the message in the `accepted` state. The SDK **does not send media, location or reactions**: `send()` accepts only `text` and `template`.

```ts theme={null}
const message = await routa.messages.send({
  channel: 'chan_...',
  to: '+5581999999999',
  text: 'Hi! Your order is confirmed.',
  metadata: { order_id: '1234' },
})

console.log(message.id, message.status) // "msg_...", "accepted"
```

| Parameter | Description |
| - | - |
| `channel` | Channel ID (`chan_...`). |
| `to` | Recipient in E.164. The leading `+` is optional. |
| `text` | Message body. Mutually exclusive with `template`. |
| `template` | `{ id, bodyParameters?, headerParameter?, buttonParameters? }`. Mutually exclusive with `text`. |
| `metadata` | Up to 20 text key-value pairs. |
| `idempotencyKey` | Reused on every retry. By default the SDK generates one. |

> [!WARNING]
>
> `accepted` does not mean delivered. Track delivery through [webhooks](https://docs.routa.chat/en/sdk/webhooks.md). See [Track delivery](https://docs.routa.chat/en/guides/track-delivery.md).

### Send a template

```ts theme={null}
await routa.messages.send({
  channel: 'chan_...',
  to: '+5581999999999',
  template: { id: 'tmpl_...', bodyParameters: ['Ana', '1234'] },
})
```

A send carries exactly what the template asks for. `headerParameter` and `buttonParameters` exist from version 0.5.0.

| The template has | Pass in `template` |
| - | - |
| Variables in the body | `bodyParameters`: one value per variable, the first one for `{{1}}`. |
| Text header with `{{1}}` | `headerParameter: { text }`. |
| Media header | `headerParameter: { mediaId }` and, on a document only, `filename`, if you want. |
| URL buttons with `{{1}}` | `buttonParameters`: one `{ index, text }` for each of those buttons. |

```ts theme={null}
// Header: 'Order {{1}}'. Body: 'Hi {{1}}, invoice {{2}} is here.'
// Buttons: 0 is a quick reply, 1 opens 'https://example.com/invoices/{{1}}'.
await routa.messages.send({
  channel: 'chan_...',
  to: '+5581999999999',
  template: {
    id: 'tmpl_...',
    bodyParameters: ['Ana', '1234'],
    headerParameter: { text: 'A-10' },
    buttonParameters: [{ index: 1, text: encodeURIComponent('march invoice') }],
  },
})
```

`index` is the position of the button in `template.components.buttons`, starting at 0, and **every** button counts. `text` is the value that replaces `{{1}}` in the URL. The API appends it as is, and the SDK does not encode it: percent-encode it yourself, only once.

For a media header, upload the file with [`media.upload()`](https://docs.routa.chat/en/sdk/media) and pass its `id`:

```ts theme={null}
import { readFile } from 'node:fs/promises'

const file = await routa.media.upload({
  file: await readFile('./invoice.pdf'),
  contentType: 'application/pdf',
})

await routa.messages.send({
  channel: 'chan_...',
  to: '+5581999999999',
  template: {
    id: 'tmpl_...',
    headerParameter: { mediaId: file.id, filename: 'invoice.pdf' },
  },
})
```

`mediaId` is a `MediaId`. The sample used to create the template, a `TemplateMediaId` from `templates.uploadMedia()`, does not compile here.

The SDK only checks the shape of the types. The API refuses the send with a `RoutaInvalidRequestError`:

| Status | `code` | When |
| - | - | - |
| `422` | `content_rejected` | A parameter is missing, extra, mismatched or empty, or holds a [value WhatsApp refuses](https://docs.routa.chat/en/guides/send-template-message.md#refused-values). Carries no `param`. |
| `404` | `media_not_found` | The header file does not belong to this project. |
| `422` | `media_not_ready` | The file is not available. |
| `422` | `media_content_type_rejected` | The file type does not match the header format. |
| `422` | `request_invalid` | A field is missing or has the wrong type. `param` names it, such as `template.button_parameters.0.index`. |

## `retrieve`

Returns a message by its ID.

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

// An ID you already trust, such as one stored from an earlier send:
const message = await routa.messages.retrieve(toMessageId('msg_01J8ZK9M3Q7XABCDEFGHJKMNPQ'))
console.log(message.status, message.deliveredAt)

// An ID that came from user input or a URL: validate the format first.
function lookUp(id: string) {
  if (!isMessageId(id)) {
    throw new Error(`Not a message id: ${id}`)
  }
  return routa.messages.retrieve(id)
}
```

IDs are *branded* types: a `MessageId` is a string at runtime, but a plain `string` is not assignable to it. See [Types and IDs](https://docs.routa.chat/en/sdk/typescript.md).

## `list`

Lists messages with automatic pagination. Filter by `direction` to see only inbound or only outbound messages.

```ts theme={null}
for await (const message of routa.messages.list({ direction: 'inbound', limit: 50 })) {
  console.log(message.id, message.from, message.content)
}
```

To control pagination yourself, ask for one page at a time:

```ts theme={null}
const page = await routa.messages.list({ limit: 20 }).page()
console.log(page.data.length, page.hasMore, page.nextCursor)
```

See [Pagination](https://docs.routa.chat/en/sdk/pagination.md).

## `markRead`

Marks an **inbound** message as read and sends the read receipt to its sender.

```ts theme={null}
const message = await routa.messages.markRead(messageId)
console.log(message.status) // "read"
```

For a message you sent, the API responds `422 message_direction_invalid`.

## The `Message` object

The SDK fields are the API fields in *camelCase*.

| Field | Type | Description |
| - | - | - |
| `id` | `MessageId` | ID. |
| `channel` | `string` | Channel used. |
| `direction` | `'outbound' \| 'inbound'` | Direction. |
| `origin` | `'api' \| 'business_app' \| null` | Who sent an `outbound` message. `api` is a message sent through Routa. `business_app` is a message the business sent from the WhatsApp Business app, on a channel in coexistence mode. It is `null` on an `inbound` message. Available from 0.3.0. |
| `from`, `to` | `string` | Addresses in E.164. |
| `content` | `MessageContent \| null` | Content, discriminated by `type`. It is `null` when retention removed the content. Available from 0.2.0. |
| `status` | `MessageStatus` | `accepted`, `sent`, `delivered`, `read` or `failed`. |
| `failureCode` | `string \| null` | Reason for the failure. It only has a value when `status` is `failed`. Available from 0.3.0. |
| `metadata` | `Record<string, string>` | Your metadata. |
| `acceptedAt` | `string` | ISO 8601, always present. |
| `sentAt`, `deliveredAt`, `readAt`, `failedAt` | `string \| null` | Time of each step. |
| `contentRedactedAt` | `string \| null` | ISO 8601. When retention removed the content, or `null` while the message still has it. Available from 0.2.0. |
| `_replayed` | `boolean` | `true` when the call returned the result of an earlier attempt with the same `Idempotency-Key`. |

### Messages sent from the WhatsApp Business app

On a channel in coexistence mode, the business can also send messages from the WhatsApp Business app. Routa records them as `outbound` with `origin: 'business_app'`. They are not sent through Routa, use none of your allowance and do not appear in usage. Use `origin` to tell them apart from the messages your code sent. See [Messages](https://docs.routa.chat/en/concepts/messages.md).

```ts theme={null}
for await (const message of routa.messages.list({ direction: 'outbound' })) {
  if (message.origin === 'business_app') {
    console.log(message.id, 'sent from the app, not the API')
  }
}
```

### Failed messages

`failureCode` is the reason for the failure of a message with `status: 'failed'`, and `null` otherwise. The set of codes is closed and belongs to Routa, but the API publishes it as a `string`, so the SDK does not narrow it to a union. Compare it with the codes you handle and treat any other value as "failed, reason unknown". Among them, `media_unavailable` means a file of the message became unavailable before sending, and `provider_payment_issue`, that WhatsApp refused the send because of the account's payment method. See [Failure reasons](https://docs.routa.chat/en/concepts/messages.md#failure-reasons).

```ts theme={null}
const message = await routa.messages.retrieve(messageId)

if (message.status === 'failed') {
  console.error(message.id, message.failureCode ?? 'unknown')
}
```

### Messages with removed content

Routa removes the content of a message after the retention period of your plan. The API returns that message with `content: null` and `content_redacted_at`. The rest of it stays. See [Content removed by retention](https://docs.routa.chat/en/concepts/messages.md#content-removed-by-retention).

Since 0.2.0, `content` is `MessageContent | null` and `contentRedactedAt` is `string | null`. These messages are returned as usual. Guard your reads of `message.content`:

```ts theme={null}
for await (const message of routa.messages.list({ limit: 50 })) {
  if (message.content) {
    console.log(message.id, message.content.type)
  } else {
    console.log(message.id, 'content removed at', message.contentRedactedAt)
  }
}
```

> [!NOTE]
>
> In version 0.1.0, `messages.retrieve()` and `messages.list()` throw a `TypeError` when they meet a message with removed content, and a single one of those messages breaks the whole listing. Upgrade to the current version. See [Upgrade to 0.3.0](https://docs.routa.chat/en/sdk/upgrading.md).

Since 0.5.0, the content of a template carries `header_parameter` and `button_parameters`, in *snake\_case* like the rest of `content`. The keys are absent when the template asks for nothing there.

`MessageContent` also covers types that only arrive in inbound messages or in the history (media, location, reaction) and `unsupported`, so that reading a message does not throw just because its content type cannot be sent yet. This is separate from the `null` described above, which means removed content, not an unknown type.


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