> For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt.

# SMS

`@dotpress/sms` sends SMS through interchangeable providers: Twilio, Telnyx, Vonage, OVHcloud, Brevo and Amazon SNS. Every provider calls its API with `fetch`: no SDK, no dependency. It works in a route, a worker or a script.


```sh [npm]
npm install @dotpress/sms
```

```sh [yarn]
yarn add @dotpress/sms
```

```sh [pnpm]
pnpm add @dotpress/sms
```

```sh [bun]
bun add @dotpress/sms
```

```sh [deno]
deno add npm:@dotpress/sms
```

## Sending

```ts
import { createSms } from '@dotpress/sms'
import { createTwilioProvider } from '@dotpress/sms/twilio'

const sms = createSms({
  provider: createTwilioProvider({
    accountSid: env.TWILIO_ACCOUNT_SID,
    authToken: env.TWILIO_AUTH_TOKEN,
  }),
  from: '+15005550006',
})

const { messageId } = await sms.send({ to: '+33612345678', text: '123456 is your login code.' })
```

`to` is a phone number in E.164 format: `+`, the country code, then the number, without spaces. Normalize the numbers when you store them: `send()` rejects any other format, without the number in the error, as errors end up in logs.

`from` is the sender, required: a phone number in E.164 format, a short code or an alphanumeric sender ID (`Acme`, 11 characters at most), as your provider and the destination country accept. `send()` takes a `from` that replaces the default one.

`send()` returns the `messageId` given by the provider. `createSms()` also takes a `logger` that logs each sent message, without the number nor the text.

## Second factor of the auth

The client fits the `sms` option of `createAuthMessages()` of `@dotpress/auth/messages`, which sends the codes of the SMS second factor (`mfa.sms`). The auth package does not depend on this one: any object with a `send({ to, text })` method fits.

```ts
import { createAuthMessages } from '@dotpress/auth/messages'

const messages = createAuthMessages({ mailer, sms })
```

## Providers

| Provider                   | Import                   | Use                              |
| -------------------------- | ------------------------ | -------------------------------- |
| `createMemoryProvider()`   | `@dotpress/sms`          | tests: keeps the messages        |
| `createConsoleProvider()`  | `@dotpress/sms`          | development: prints the messages |
| `createTwilioProvider()`   | `@dotpress/sms/twilio`   | Twilio                           |
| `createTelnyxProvider()`   | `@dotpress/sms/telnyx`   | Telnyx                           |
| `createVonageProvider()`   | `@dotpress/sms/vonage`   | Vonage (Messages API)            |
| `createOvhcloudProvider()` | `@dotpress/sms/ovhcloud` | OVHcloud                         |
| `createBrevoProvider()`    | `@dotpress/sms/brevo`    | Brevo (transactional SMS)        |
| `createSnsProvider()`      | `@dotpress/sms/aws-sns`  | Amazon SNS                       |

Switching provider changes one line: the calls stay the same. A provider is an object with a `name` and a `send(message)` method: write your own for another service. The settings of each provider are in the [SMS reference](https://dotpress.dev/reference/sms.md#providers).

:::warning Never fall back to the console provider
The console provider is for development. In production, a missing provider configuration must fail at startup: falling back to the console would lose every message silently, login codes included.
:::

### Amazon SNS

The provider signs its requests itself: it has no AWS credential chain. Pass the credentials, or a function returning them, called for each message. A credential provider of the AWS SDK fits, and refreshes temporary credentials:

```ts
import { createSnsProvider } from '@dotpress/sms/aws-sns'
import { fromNodeProviderChain } from '@aws-sdk/credential-providers'

const provider = createSnsProvider({ region: 'eu-west-3', credentials: fromNodeProviderChain() })
```

On AWS Lambda, the environment holds the credentials of the role: `{ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, sessionToken: process.env.AWS_SESSION_TOKEN }`. The role needs the `sns:Publish` permission. A new account sends in the SMS sandbox, to verified numbers only, until AWS moves it to production.

## Testing

The memory provider keeps the messages:

```ts
const outbox = createMemoryProvider()
const sms = createSms({ provider: outbox, from: 'Acme' })

await requestLoginCode(sms, '+33612345678')

expect(outbox.last()).toMatchObject({ to: '+33612345678', from: 'Acme' })
expect(outbox.last()?.text).toMatch(/^\d{6} is your login code/)
```

`outbox.sent` lists the messages, `clear()` empties it.

## Errors

| Error             | When                                                |
| ----------------- | --------------------------------------------------- |
| `SmsMessageError` | invalid phone number or sender, empty text          |
| `SmsSendError`    | the provider failed (`provider`, `status`, `cause`) |

Sending is neither queued nor retried. For messages that must arrive despite a provider outage, send them from an [event listener](https://dotpress.dev/services/events.md). See the [SMS reference](https://dotpress.dev/reference/sms.md) for every option.
