Skip to content
SMS SDK
Esc
↑↓navigate↵open⌘Jpreview
On this page

Twilio SMS API with TypeScript: send safely and test without a carrier

Send SMS through the Twilio Message resource from TypeScript, verify X-Twilio-Signature behind a proxy, fall back safely, and test offline with signed fixtures.

This guide takes a TypeScript server from Twilio credentials to a verified status callback, and makes the risky parts safe: who can trigger a send, what happens when Twilio times out, and how to test all of it without a phone. You send one SMS with the raw Message resource, verify a signed callback by hand, then build the same thing with the SMS SDK twilio() adapter and test it offline. It doesn’t replace Twilio’s Messaging API reference; it links to it where details matter. The second half of the page is the adapter reference. To compare providers first, see Choose a provider.

Support status

Supported. Requests, responses, error codes, statuses, and webhook signing follow Twilio’s official documentation, and the adapter passes the shared contract tests. Limits to know:

  • Scheduling (sendAt) works only from a Messaging Service sender.
  • Content Templates (ContentSid) are not supported.
  • Webhook verification needs the Auth Token of the account that owns the number. An API key cannot verify webhooks.
  • Twilio signs no timestamp, so webhooks have no replay window. Deduplicate on dedupeKey.

Before you start

Credentials. Twilio has two kinds, and a production app usually needs both:

  • An API key (an SK SID plus a secret) authenticates your requests to the REST API. Twilio recommends API keys because you can create one per service and revoke it without touching anything else.
  • The Auth Token is the account’s master secret. Twilio signs every webhook it sends with it, so your server needs it to verify status callbacks and inbound messages. An API key can’t verify a webhook.

Every request also names your Account SID (AC plus 32 hex characters) in the URL.

Sender. A message goes out either from a specific number (From) or through a Messaging Service (MessagingServiceSid), a group of senders with shared settings. With a Messaging Service and no From, Twilio picks a number from the service’s sender pool and the new message starts in status accepted instead of queued. Use one for production in the US: A2P 10DLC registration attaches your numbers to a service, and the service holds the status callback URL, the incoming message webhook, and Advanced Opt-Out.

Trial accounts. A trial can text only verified numbers, at most five, in your sign-up country, using Twilio’s predefined message templates rather than your own text, and it expires after 30 days. Sending to anyone else fails with error 21608. So a trial shows that your credentials work but can’t run your real message flow; see Free trial limitations (checked 2026-10-28).

US registration. Texting US mobile numbers from a +1 long code (10DLC) needs an approved A2P 10DLC campaign with the number in that campaign’s Messaging Service; otherwise Twilio blocks the message with error 30034. An unverified toll-free number is blocked with 30032. Neither shows up when you send: Twilio accepts the request with a 201, and the error arrives later in a status callback as undelivered. See Registration and consent.

The examples read these variables:

Variable Required Used for
TWILIO_ACCOUNT_SID Yes Account SID, AC plus 32 hex characters.
TWILIO_API_KEY_SID, TWILIO_API_KEY_SECRET Yes API auth.
TWILIO_AUTH_TOKEN For webhooks Verifying X-Twilio-Signature.
TWILIO_MESSAGING_SERVICE_SID Yes Sender, MG plus 32 hex characters.
TWILIO_WEBHOOK_URL For webhooks The exact public URL you configured in Twilio.
TELNYX_API_KEY, TELNYX_FROM Only for the optional fallback A second provider for known rejections.

The adapter reads no environment variables itself; the examples and the doctor CLI use these names. Keep the secrets on the server.

Send an SMS with the raw Message resource

Creating a Message resource sends it: one form-encoded POST to /2010-04-01/Accounts/{AccountSid}/Messages.json with HTTP Basic auth. It needs only fetch, which Node.js 18 and later have built in:

function env(name: string): string {
  const value = process.env[name];
  if (value === undefined || value === "") throw new Error(`Set ${name}.`);
  return value;
}

const accountSid = env("TWILIO_ACCOUNT_SID");
const credentials = btoa(`${env("TWILIO_API_KEY_SID")}:${env("TWILIO_API_KEY_SECRET")}`);

const response = await fetch(`https://api.twilio.com/2010-04-01/Accounts/${accountSid}/Messages.json`, {
  method: "POST",
  headers: {
    Authorization: `Basic ${credentials}`,
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json",
  },
  body: new URLSearchParams({
    To: "+14155550123",
    MessagingServiceSid: env("TWILIO_MESSAGING_SERVICE_SID"),
    Body: "Your order has shipped.",
  }),
});

const message: unknown = await response.json();
const field = (name: string): unknown =>
  typeof message === "object" && message !== null && name in message ? Reflect.get(message, name) : undefined;
// Log IDs and status only: the resource also holds the message text and phone numbers.
console.log(response.status, field("sid"), field("status"), field("code"));

With an API key, the Basic auth user is the key SID and the password is its secret. With the Auth Token, they are the Account SID and the token. A successful send prints 201, the message SID, and its status, such as 201 SM0123… accepted undefined. The response body is the new Message resource. This copy is shortened, with example SIDs:

{
  "sid": "SM0123456789abcdef0123456789abcdef",
  "account_sid": "AC0123456789abcdef0123456789abcdef",
  "messaging_service_sid": "MG0123456789abcdef0123456789abcdef",
  "to": "+14155550123",
  "from": null,
  "body": "Your order has shipped.",
  "status": "accepted",
  "num_segments": "0",
  "error_code": null,
  "direction": "outbound-api"
}

Save sid. Every status callback for this message carries it as MessageSid. from stays empty until Twilio picks a sender from the pool.

A 4xx with a code in the body means Twilio refused the message, and the code says why: 21211 is a bad To, 21610 a recipient who replied STOP. A 5xx, a timeout, or a dropped connection means you don’t know whether Twilio created the message. The Message resource documents no idempotency key, so sending again can text the person twice. Look the message up first; the Message resource list can be filtered by To and date.

Accepted is not delivered

The 201 means Twilio created and queued the message. Delivery is reported later, to the status callback URL:

Stage Raw API SMS SDK
Accepted 201 with sid, status accepted or queued send() resolves with handoff: "accepted" and delivery: "queued"
Refused 4xx with code ProviderRejectedError with a category
Outcome unknown 5xx, timeout, network error HandoffUnknownError. Never resent automatically.
Handed to the carrier Callback with MessageStatus=sent message.sent event
Delivered or failed Callback with delivered, undelivered, or failed, plus ErrorCode message.delivered, message.undelivered, or message.filtered event

Registration errors such as 30034 and 30032 arrive in that last row, not as a refusal.

Verify X-Twilio-Signature behind a proxy

Twilio signs each webhook with your Auth Token and sends the result in X-Twilio-Signature: base64 HMAC-SHA1 over the full URL it called, followed by every POST parameter’s name and value, sorted by name. Messaging webhooks are form-encoded, so this handles a form POST:

const encoder = new TextEncoder();

function byNameThenValue([nameA, valueA]: [string, string], [nameB, valueB]: [string, string]): number {
  if (nameA !== nameB) return nameA < nameB ? -1 : 1;
  return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
}

function decodeBase64(value: string) {
  try {
    return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
  } catch {
    return null;
  }
}

export async function verifyTwilioRequest(request: Request, authToken: string, publicUrl: string): Promise<URLSearchParams> {
  const signature = request.headers.get("x-twilio-signature");
  if (signature === null) throw new Error("Missing X-Twilio-Signature.");

  const params = new URLSearchParams(await request.text());
  const signed = publicUrl + [...params].sort(byNameThenValue).map(([name, value]) => name + value).join("");

  const expected = decodeBase64(signature);
  if (expected === null) throw new Error("Invalid X-Twilio-Signature.");
  const key = await crypto.subtle.importKey("raw", encoder.encode(authToken), { name: "HMAC", hash: "SHA-1" }, false, ["verify"]);
  if (!(await crypto.subtle.verify("HMAC", key, expected, encoder.encode(signed)))) {
    throw new Error("Invalid X-Twilio-Signature.");
  }
  return params;
}

crypto.subtle.verify compares in constant time. The function returns the parameters only after the check passes.

The URL is the part that breaks in production. Twilio signs the URL it called, such as https://example.com/api/webhooks/twilio. Behind a load balancer, a tunnel, or a platform router, your handler often sees something else in request.url, such as http://10.0.0.12:3000/api/webhooks/twilio, and every signature fails. So pass the exact URL you configured in Twilio as publicUrl, from your own config, not from the request:

  • Keep the query string if the configured URL has one; it is signed.
  • Leave out a # fragment. Twilio’s connection overrides live there, and Twilio doesn’t sign it.
  • Twilio sometimes signs the URL with an explicit :443 or :80. This function doesn’t try both forms; SMS SDK does.
  • Don’t build the URL from X-Forwarded-Host unless a proxy you control sets it, because a client can send that header too.

You still have to map statuses, drop repeated callbacks, and record opt-outs, which is what the SMS SDK version below does.

Test with Twilio’s test credentials

Twilio has its own way to exercise the API without sending: test credentials, a separate Account SID and Auth Token. They belong to Twilio’s legacy console: test credentials created there before the console migration keep working, but Twilio points new accounts to a trial account instead (checked 2026-10-28). Without them, use the offline tests below. Requests made with them are validated like live ones, but Twilio sends nothing, doesn’t charge the account, and doesn’t change account state. Magic numbers make the response predictable:

Parameter Magic number Result
From +15005550006 Passes validation
From +15005550001 21212, invalid number
From +15005550007 21606, not owned by the account or not SMS-capable
To +15005550001 21211, invalid number
To +15005550004 21610, recipient has opted out
To +15005550009 21614, can’t receive SMS

The full list, with more To and From cases, is on Twilio’s page. The twilio() adapter works with them, so you can check how your code reacts to a real Twilio refusal:

import { createSmsClient, ProviderRejectedError } from "@opencoredev/sms-sdk";
import { twilio } from "@opencoredev/sms-sdk/twilio";

const sms = createSmsClient({
  adapters: [
    twilio({
      accountSid: process.env.TWILIO_TEST_ACCOUNT_SID ?? "",
      authToken: process.env.TWILIO_TEST_AUTH_TOKEN ?? "",
      from: "+15005550006",
    }),
  ],
});

for (const to of ["+15005550004", "+15005550009"] as const) {
  try {
    await sms.send({ to, body: "Test message" });
  } catch (error) {
    if (!(error instanceof ProviderRejectedError)) throw error;
    console.log(to, error.category, error.provider?.code);
  }
}
// +15005550004 compliance 21610
// +15005550009 recipient 21614

Test credentials have limits. They don’t support MessagingServiceSid, they never trigger status callbacks, and every run still needs the network and Twilio. So they cover the request, not the parts that usually break: your fallback rules, your opt-out list, and your webhook handler. The offline tests below cover those with memory() adapters and signed webhook fixtures, and need no account.

Common setup errors

What you see Cause Fix
401, error 20003 Wrong credentials, or an API key SID used with the Auth Token Pair the key SID with its secret, or the Account SID with the Auth Token.
400, error 21608 Trial account sending to an unverified number Verify the number, or upgrade the account.
400, error 21606 From isn’t a number on this account, or can’t send SMS Use a number you own, or send through the Messaging Service.
400, error 21211 To isn’t a valid number Send E.164, such as +14155550123.
400, error 21610 The recipient replied STOP Don’t send until they reply START.
201, then undelivered with 30034 US 10DLC number without an approved A2P campaign Register the brand and campaign, and put the number in the campaign’s Messaging Service.
201, then undelivered with 30032 Unverified toll-free number Complete toll-free verification.
201, then undelivered with 30007 Twilio or the carrier filtered the content Read Twilio’s filtering guidance; don’t retry the same text.
Every signature fails request.url isn’t the URL Twilio called, or the Auth Token belongs to another account Pass the configured URL as publicUrl; use the token of the account (or subaccount) that owns the number.
No status callbacks No callback URL on the service or message, or test credentials Set the Messaging Service’s status callback URL. Test credentials never send callbacks.

The full error mapping is in Error codes.

Build it with SMS SDK

The SMS SDK version is one module plus two small Next.js routes. It sends with twilio() through your Messaging Service, optionally falls back to Telnyx when Twilio proves it refused the message for an account reason, stops on an unknown outcome, and verifies every webhook before it reads it.

npm install @opencoredev/sms-sdk
pnpm add @opencoredev/sms-sdk
yarn add @opencoredev/sms-sdk
bun add @opencoredev/sms-sdk
nub add @opencoredev/sms-sdk
aube add @opencoredev/sms-sdk

1. Create the client and handlers

import {
  AllProvidersRejectedError,
  createSmsClient,
  HandoffUnknownError,
  isE164,
  memoryIdempotencyStore,
  PolicyRejectedError,
  ProviderRejectedError,
  type E164,
  type SmsAdapter,
  type SmsClient,
} from "@opencoredev/sms-sdk";
import { telnyx } from "@opencoredev/sms-sdk/telnyx";
import { twilio } from "@opencoredev/sms-sdk/twilio";
import { parseSmsWebhook, WebhookSignatureError, type SmsEvent } from "@opencoredev/sms-sdk/webhooks";
import { db } from "@/db";

function env(name: string): string {
  const value = process.env[name];
  if (value === undefined || value === "") throw new Error(`Set ${name}.`);
  return value;
}

function telnyxFallback(): SmsAdapter[] {
  const { TELNYX_API_KEY, TELNYX_FROM } = process.env;
  if (TELNYX_API_KEY === undefined || TELNYX_FROM === undefined) return [];
  if (!isE164(TELNYX_FROM)) throw new Error("TELNYX_FROM must be an E.164 number.");
  return [telnyx({ apiKey: TELNYX_API_KEY, from: TELNYX_FROM })];
}

/** Your send policy. Tests pass memory() adapters; the app passes real ones. */
export function createSms(adapters: readonly [SmsAdapter, ...SmsAdapter[]]): SmsClient {
  return createSmsClient({
    adapters,
    fallback: "on-known-rejection",
    // Checked before any provider request, so the fallback can't text someone who replied STOP.
    beforeSend: async ({ message }) =>
      (await db.suppressions.has(message.to)) ? { kind: "reject", reason: "opted_out" } : { kind: "allow" },
    // Lost on restart and not shared between instances. Use a durable store in production.
    idempotency: { store: memoryIdempotencyStore() },
  });
}

let live: SmsClient | undefined;

export function liveSms(): SmsClient {
  live ??= createSms([
    twilio({
      accountSid: env("TWILIO_ACCOUNT_SID"),
      apiKeySid: env("TWILIO_API_KEY_SID"),
      apiKeySecret: env("TWILIO_API_KEY_SECRET"),
      from: { messagingService: env("TWILIO_MESSAGING_SERVICE_SID") },
    }),
    ...telnyxFallback(),
  ]);
  return live;
}

export type SendOutcome =
  | { readonly kind: "accepted"; readonly provider: string; readonly providerId: string }
  | { readonly kind: "rejected"; readonly reason: string }
  | { readonly kind: "unknown" };

export async function sendSms(sms: SmsClient, input: { to: E164; body: string; idempotencyKey: string }): Promise<SendOutcome> {
  try {
    const result = await sms.send(input);
    // Upsert: a replayed send returns the original result, and a status callback may have created the row first.
    await db.messages.saveSent({ id: result.id, provider: result.provider, providerId: result.providerId, to: input.to, status: result.delivery });
    return { kind: "accepted", provider: result.provider, providerId: result.providerId };
  } catch (error) {
    if (error instanceof HandoffUnknownError) {
      // Twilio may have created the message. Never resend; reconcile it first.
      await db.messages.markNeedsReview(input.idempotencyKey, error.reason);
      return { kind: "unknown" };
    }
    if (error instanceof PolicyRejectedError) return { kind: "rejected", reason: error.reason };
    if (error instanceof ProviderRejectedError) {
      // 21610: the recipient replied STOP to your Twilio sender. Remember it for every provider.
      if (error.providerName === "twilio" && error.provider?.code === "21610") await db.suppressions.add(input.to);
      return { kind: "rejected", reason: error.category };
    }
    if (error instanceof AllProvidersRejectedError) {
      return { kind: "rejected", reason: error.errors.map((rejection) => `${rejection.providerName}: ${rejection.category}`).join(", ") };
    }
    throw error;
  }
}

export async function handleTwilioWebhook(request: Request): Promise<Response> {
  let event: SmsEvent;
  try {
    event = await parseSmsWebhook({
      provider: "twilio",
      request,
      publicUrl: env("TWILIO_WEBHOOK_URL"),
      credentials: { authToken: env("TWILIO_AUTH_TOKEN") },
    });
  } catch (error) {
    if (error instanceof WebhookSignatureError) return new Response("Invalid signature", { status: 401 });
    throw error;
  }

  // Record the event key and its effects together, so a failed write rolls both back.
  await db.transaction(async (tx) => {
    if (!(await tx.webhookEvents.insertIfNew(event.dedupeKey))) return;
    switch (event.type) {
      case "message.queued":
      case "message.sent":
      case "message.delivered":
      case "message.undelivered":
      case "message.filtered":
        await tx.messages.updateStatus(event.providerId, event.type, event.errorCode);
        break;
      case "recipient.opted_out":
        await tx.suppressions.add(event.from);
        break;
      case "recipient.opted_in":
      case "recipient.help":
      case "message.received":
        await tx.inbox.save({ from: event.from, to: event.to, body: event.body, providerId: event.providerId });
        break;
      case "unrecognized":
        break;
      default: {
        const _exhaustive: never = event;
        return _exhaustive;
      }
    }
  });
  // Empty TwiML: no automatic reply to inbound messages.
  return new Response("<Response></Response>", { headers: { "content-type": "text/xml" } });
}

sendSms() returns one of three outcomes. accepted names the provider that took the message. rejected means no provider took it: the recipient is on your opt-out list (checked by beforeSend before any request), or the providers refused it. unknown means a timeout, network error, or 5xx left the result unclear; the message is flagged for review and never resent, even when Telnyx is configured.

The fallback runs only after a Twilio rejection that belongs to your Twilio setup, such as bad credentials (20003) or an unusable sender (21606), because those say nothing about the recipient. A bad number (21211) or an opt-out (21610) stops there, because Telnyx would fail the same way or shouldn’t send at all. Registration blocks like 30034 arrive after acceptance, so they never trigger a fallback; handle them from status callbacks. See Fallback and retries.

A retry with the same idempotency key returns the stored result of an accepted send, and stays unknown after an unknown one, instead of sending again. After a known rejection, the same key can send again, but only with the same message: a retry after you fix the cause on the account side (credentials, sender, registration) does send. Changing the recipient or the text under that key throws IdempotencyConflictError, so use a new key for a corrected message. That matters more on Twilio than elsewhere, because Twilio has no idempotency key of its own. memoryIdempotencyStore() forgets outcomes when the process restarts, so before production swap it for a durable store such as the Postgres store.

handleTwilioWebhook() answers 401 to forged requests and 200 to a repeat without handling it twice. dedupeKey is twilio:{MessageSid}:{MessageStatus} for status callbacks and twilio:{MessageSid}:received for inbound messages. Because Twilio signs every parameter, a replayed request can’t change the status, so that key is enough. Insert it with a unique constraint (INSERT ... ON CONFLICT DO NOTHING) in the same transaction as the writes it guards: if a write fails, the key rolls back with it and the handler answers 500. Twilio doesn’t guarantee callback order, and a callback can arrive before saveSent runs. So updateStatus must upsert by providerId and keep the furthest status (delivered never goes back to sent), and saveSent must fill in the send details without touching a status that is already there.

By Twilio’s connection override defaults, a webhook is retried once, and only when Twilio can’t connect; a 500 from your handler isn’t retried. To get retries after a failed write, add overrides such as #rc=3&rp=5xx to the URL you configure in Twilio, and keep TWILIO_WEBHOOK_URL without the fragment. Otherwise, reconcile missed statuses by fetching the message.

Opt-outs arrive as recipient.opted_out with source: "provider" when Advanced Opt-Out is on for the Messaging Service, and Twilio’s OptOutType then also reports START and HELP. Without it, SMS SDK matches STOP and HELP keywords in the text (source: "keyword"), and a START reply arrives as an ordinary message.received. The switch handles every event type, so TypeScript flags any new one.

A START reply goes to the inbox and doesn’t clear the suppression on its own. Inbound webhooks carry no timestamp, and two replies sent close together can be handled in either order, so a late START could undo a newer STOP. Clear the suppression from your own code once you’ve confirmed that START is the number’s latest reply, for example by checking its most recent inbound message in Twilio.

The routes below import this module as @/twilio-sms, so save it, db.ts, and auth.ts at your project root, which is where the default @/* alias of create-next-app points. Add import "server-only"; to this module so the secrets can never reach a client bundle, and never prefix these variables with NEXT_PUBLIC_. If you configure Telnyx, its webhooks need their own route; see Telnyx.

2. Protect the send route

A route that texts any number its caller names is an open SMS relay: anyone who finds it can spend your balance and get your sender flagged by carriers. Require a signed-in user, and take the recipient and text from your own data, never from the request:

import { isE164 } from "@opencoredev/sms-sdk";
import { getSession } from "@/auth";
import { db } from "@/db";
import { liveSms, sendSms } from "@/twilio-sms";

export const runtime = "nodejs";

export async function POST(request: Request): Promise<Response> {
  const session = await getSession(request);
  if (session === null) return new Response("Unauthorized", { status: 401 });

  const input: unknown = await request.json().catch(() => null);
  const orderId = typeof input === "object" && input !== null && "orderId" in input ? input.orderId : undefined;
  if (typeof orderId !== "string") return new Response("orderId is required", { status: 400 });

  const order = await db.orders.findForUser(orderId, session.userId);
  if (order === null || !isE164(order.phone)) return new Response("Order not found", { status: 404 });
  if (order.status !== "shipped") return new Response("Order has not shipped", { status: 409 });

  const outcome = await sendSms(liveSms(), {
    to: order.phone,
    body: `Order ${order.id} has shipped.`,
    idempotencyKey: `order:${order.id}:shipped`,
  });
  switch (outcome.kind) {
    case "accepted":
      return Response.json(outcome, { status: 200 });
    case "rejected":
      return Response.json(outcome, { status: 422 });
    case "unknown":
      return Response.json(outcome, { status: 202 });
    default: {
      const _exhaustive: never = outcome;
      return _exhaustive;
    }
  }
}

getSession stands for your auth library, and db.orders.findForUser returns an order only to its owner. The idempotency key ties the text to the order, so a double click or a retried request sends one message while the key is stored, which is 24 hours by default (idempotency.ttlSec). To send one shipping text per order ever, also record on the order that it went out. Add a per-user rate limit as well. In most apps the shipping text is sent by the code that marks the order shipped; the route shows how to guard one a user can trigger.

3. Receive status callbacks in Next.js

import { handleTwilioWebhook } from "@/twilio-sms";

export const runtime = "nodejs";

export async function POST(request: Request): Promise<Response> {
  return handleTwilioWebhook(request);
}

The route hands the untouched Request to the handler. Don’t call request.formData() or request.text() first, and keep middleware from reading the body, because a body can be read only once. Next.js does not cache POST handlers. SMS SDK is tested on Node.js and Bun, which is why the route sets runtime = "nodejs".

In the Twilio Console, open your Messaging Service and set both its status callback URL and its incoming message webhook (HTTP POST) to this route’s public HTTPS URL, then put the same URL in TWILIO_WEBHOOK_URL. The code doesn’t pass webhookUrl per message on purpose: with a fallback configured, a per-message URL would go to Telnyx too, and Telnyx’s webhooks would land on a route that checks Twilio signatures. Twilio waits up to 15 seconds for a response, so store the event and return; do slow work later. To reach your laptop, expose the port with a tunnel and set TWILIO_WEBHOOK_URL to the tunnel URL; see Test without a provider.

4. Test it offline

These tests send nothing and need no Twilio account or network. App logic runs against memory() adapters, the Twilio error mapping runs through the real twilio() adapter with a fake fetch, and webhook fixtures are signed with a test Auth Token, so the real signature check runs:

import { expect, mock, spyOn, test } from "bun:test";
import { memory, mockFetch, rejectedOutcome, signedTwilioRequest, type MockReply } from "@opencoredev/sms-sdk/testing";
import { twilio } from "@opencoredev/sms-sdk/twilio";
import { db } from "./db";

const publicUrl = "https://example.com/api/webhooks/twilio";
Object.assign(process.env, { TWILIO_AUTH_TOKEN: "test-auth-token", TWILIO_WEBHOOK_URL: publicUrl });
// `server-only` throws outside a Next.js server build, so stub it before loading the module.
mock.module("server-only", () => ({}));
const { createSms, handleTwilioWebhook, sendSms } = await import("./twilio-sms");

function fakeTwilio(reply: MockReply) {
  const api = mockFetch(reply);
  const adapter = twilio({
    accountSid: "AC0123456789abcdef0123456789abcdef",
    authToken: "test",
    from: { messagingService: "MG0123456789abcdef0123456789abcdef" },
    fetch: api.fetch,
  });
  return { api, adapter };
}

const to = "+14155550123";

test("a retried send texts once", async () => {
  const primary = memory({ name: "twilio" });
  const sms = createSms([primary]);
  const first = await sendSms(sms, { to, body: "Order 1 has shipped.", idempotencyKey: "order:1:shipped" });
  const retry = await sendSms(sms, { to, body: "Order 1 has shipped.", idempotencyKey: "order:1:shipped" });
  expect(first).toEqual({ kind: "accepted", provider: "twilio", providerId: "twilio_1" });
  expect(retry).toEqual(first);
  expect(primary.sent).toHaveLength(1);
});

test("an opted-out recipient gets nothing from any provider", async () => {
  spyOn(db.suppressions, "has").mockResolvedValueOnce(true);
  const primary = memory({ name: "twilio" });
  const backup = memory({ name: "telnyx" });
  const outcome = await sendSms(createSms([primary, backup]), { to, body: "Order 2 has shipped.", idempotencyKey: "order:2:shipped" });
  expect(outcome).toEqual({ kind: "rejected", reason: "opted_out" });
  expect([primary.sent.length, backup.sent.length]).toEqual([0, 0]);
});

test("a 21610 refusal is remembered and not retried elsewhere", async () => {
  const add = spyOn(db.suppressions, "add").mockResolvedValue();
  const primary = memory({ name: "twilio", outcomes: [rejectedOutcome("compliance", { provider: "twilio", code: "21610" })] });
  const backup = memory({ name: "telnyx" });
  const outcome = await sendSms(createSms([primary, backup]), { to, body: "Order 3 has shipped.", idempotencyKey: "order:3:shipped" });
  expect(outcome).toEqual({ kind: "rejected", reason: "compliance" });
  expect(backup.sent).toHaveLength(0);
  expect(add).toHaveBeenCalledWith(to);
  add.mockRestore();
});

test("Twilio error 21606 falls back to Telnyx", async () => {
  const { api, adapter } = fakeTwilio({ status: 400, body: { code: 21606, message: "The From phone number is not a valid, SMS-capable inbound phone number", status: 400 } });
  const backup = memory({ name: "telnyx" });
  const outcome = await sendSms(createSms([adapter, backup]), { to, body: "Order 4 has shipped.", idempotencyKey: "order:4:shipped" });
  expect(outcome).toEqual({ kind: "accepted", provider: "telnyx", providerId: "telnyx_1" });
  expect(api.calls).toHaveLength(1);
});

test("a Twilio 503 stops without trying Telnyx", async () => {
  const { adapter } = fakeTwilio({ status: 503, body: "Service Unavailable" });
  const backup = memory({ name: "telnyx" });
  const outcome = await sendSms(createSms([adapter, backup]), { to, body: "Order 5 has shipped.", idempotencyKey: "order:5:shipped" });
  expect(outcome).toEqual({ kind: "unknown" });
  expect(backup.sent).toHaveLength(0);
});

function deliveredCallback() {
  return { MessageSid: `SM${crypto.randomUUID().replaceAll("-", "")}`, MessageStatus: "delivered", To: to };
}

test("a signed status callback is recorded once", async () => {
  const updateStatus = spyOn(db.messages, "updateStatus");
  const params = deliveredCallback();
  const first = await handleTwilioWebhook(await signedTwilioRequest({ authToken: "test-auth-token", url: publicUrl, params }));
  const repeat = await handleTwilioWebhook(await signedTwilioRequest({ authToken: "test-auth-token", url: publicUrl, params }));
  expect([first.status, repeat.status]).toEqual([200, 200]);
  expect(updateStatus).toHaveBeenCalledTimes(1);
  expect(updateStatus).toHaveBeenCalledWith(params.MessageSid, "message.delivered", undefined);
  updateStatus.mockRestore();
});

test("a callback seen behind a proxy still verifies", async () => {
  const signed = await signedTwilioRequest({ authToken: "test-auth-token", url: publicUrl, params: deliveredCallback() });
  const behindProxy = new Request("http://10.0.0.12:3000/api/webhooks/twilio", {
    method: "POST",
    headers: signed.headers,
    body: await signed.text(),
  });
  expect((await handleTwilioWebhook(behindProxy)).status).toBe(200);
});

test("a forged callback is refused", async () => {
  const forged = await signedTwilioRequest({ authToken: "wrong-token", url: publicUrl, params: deliveredCallback() });
  expect((await handleTwilioWebhook(forged)).status).toBe(401);
});

Run bun test with db pointing at a test database. If your db.transaction hands the callback a separate client, spy on that client’s updateStatus instead. The output looks like this:

twilio-sms.test.ts:
(pass) a retried send texts once [2.83ms]
(pass) an opted-out recipient gets nothing from any provider [0.71ms]
(pass) a 21610 refusal is remembered and not retried elsewhere [0.32ms]
(pass) Twilio error 21606 falls back to Telnyx [1.07ms]
(pass) a Twilio 503 stops without trying Telnyx [0.28ms]
(pass) a signed status callback is recorded once [1.52ms]
(pass) a callback seen behind a proxy still verifies [0.22ms]
(pass) a forged callback is refused [0.27ms]

 8 pass
 0 fail
 17 expect() calls
Ran 8 tests across 1 file. [13.00ms]

Before the first live send, npx @opencoredev/sms-sdk doctor --adapter twilio checks your variables and sender without sending anything. See Doctor CLI.

Adapter options

import { createSmsClient } from "@opencoredev/sms-sdk";
import { twilio } from "@opencoredev/sms-sdk/twilio";

const sms = createSmsClient({
  adapters: [
    twilio({
      accountSid: process.env.TWILIO_ACCOUNT_SID ?? "",
      authToken: process.env.TWILIO_AUTH_TOKEN ?? "",
      // Or, instead of authToken: apiKeySid and apiKeySecret.
      from: "+15550100001",
    }),
  ],
});

const result = await sms.send({ to: "+14155550123", body: "Your order has shipped." });
console.log(result.providerId); // "SM..." ("MM..." for MMS)

Pass either authToken or apiKeySid with apiKeySecret, not both. twilio() throws ConfigurationError at startup when the Account SID is malformed or a credential is empty. Two more options exist for tests and proxies: baseUrl (default https://api.twilio.com) and fetch. To test without a Twilio account, see Test without a provider.

The adapter calls POST /2010-04-01/Accounts/{AccountSid}/Messages.json with a form body. A 2xx without a valid SM or MM SID is an unknown outcome.

Senders

Sender Write Sent as
Long code or toll-free number "+15550100001" From
Short code { shortCode: "12345" } From
Alphanumeric sender ID { senderId: "Acme" } From
Messaging Service { messagingService: "MG…" } MessagingServiceSid

Which senders work depends on the destination country, and a sender Twilio refuses is a sender rejection. In the US, long codes need A2P 10DLC registration, toll-free numbers need verification before they reach the US or Canada, and alphanumeric sender IDs are not supported. Twilio’s SMS guidelines list the rules for each country. SMS SDK does not check them before sending; see Registration and consent.

Features

Feature Twilio
MMS Up to 10 mediaUrls
Scheduling (sendAt) Only with a { messagingService } sender, inside Twilio’s scheduling window
Validity period 1 to 36000 seconds
Per-message webhookUrl Yes, sent as StatusCallback
Body length Up to 1600 characters, checked before sending

Provider options

Pass other Twilio Message parameters in providerOptions.twilio:

import { sms } from "./sms";

await sms.send({
  to: "+14155550123",
  body: "Track your order: https://example.com/orders/123",
  providerOptions: { twilio: { smartEncoded: true, messageIntent: "delivery" } },
});
Option Twilio parameter Type
applicationSid ApplicationSid string, AP plus 32 hex characters
provideFeedback ProvideFeedback boolean
attempt Attempt integer, 1 or more
contentRetention ContentRetention "retain" | "discard"
addressRetention AddressRetention "retain" | "obfuscate"
smartEncoded SmartEncoded boolean
shortenUrls ShortenUrls boolean. Needs a { messagingService } sender, or the send throws UnsupportedFieldError.
sendAsMms SendAsMms boolean
messageIntent MessageIntent "otp" | "notifications" | "marketing" | "fraud" | "security" | "customercare" | "delivery" | "education" | "polling" | "announcements" | "events"
riskCheck RiskCheck "enable" | "disable"
extra any other parameter Record<string, string | number | boolean>, sent as is

Unknown keys and wrong types throw before any request, and the options go out only when the twilio adapter sends. extra cannot set the fields SMS SDK owns: To, From, MessagingServiceSid, Body, MediaUrl, StatusCallback, ValidityPeriod, SendAt, ScheduleType, ContentSid, and ContentVariables. MaxPrice, ForceDelivery, and TrafficType have no typed option; send them through extra. See providerOptions for how options interact with fallback and idempotency.

Webhooks

The handler in Build it with SMS SDK is the full example. What it relies on:

  • Credential: the Auth Token of the account that owns the number. A subaccount’s number is signed with the subaccount’s token. API keys cannot verify.
  • Point Twilio at it: for status, pass webhookUrl per message or set a status callback on the Messaging Service. For inbound, set “A message comes in” on the number, or the incoming message webhook on the Messaging Service, with HTTP POST.
  • publicUrl: pass the exact URL configured in Twilio, or verification fails behind a proxy. SMS SDK also tries it with and without :443 or :80. See Webhook security.
  • Signing: X-Twilio-Signature is an HMAC-SHA1 over the URL and the sorted form parameters. For JSON bodies, Twilio signs only the URL and adds a bodySHA256 query parameter, which SMS SDK checks against the raw body.
  • Replay window: none, because Twilio signs no timestamp. Deduplicate on dedupeKey.
Twilio status Event
queued, accepted, scheduled, sending message.queued
sent message.sent
delivered message.delivered
undelivered, failed message.undelivered, or message.filtered with error 30007
read, canceled, others unrecognized
Inbound message message.received
Inbound with OptOutType STOP, START, HELP recipient.opted_out, recipient.opted_in, recipient.help (source: "provider")

OptOutType appears when Advanced Opt-Out is on for the Messaging Service. dedupeKey is twilio:{MessageSid}:{status} for status updates and twilio:{MessageSid}:received for inbound messages.

Limitations

  • Scheduling needs a Messaging Service sender. To schedule from a plain number, use Telnyx.
  • Content Templates are not supported, because a template replaces body, which SMS SDK needs for segment estimates, policy checks, and idempotency. WhatsApp and Conversations are out of scope.
  • Twilio enforces its own scheduling window and MMS country coverage, and rejects sends outside them.

Error codes

Twilio response Category Falls back
401, or error 20003 auth Yes
403 with an unlisted code auth Yes
Error 20429 rate_limited Yes, after retries
21212, 21606, 21612, 21659, 21660, 21703 sender Yes
21408 (geographic permission), 21608 (trial account) account Yes
21211, 21614 recipient No
21610 (recipient unsubscribed) compliance Never
Any other 4xx request No
429 without error 20429 unknown Never
5xx, network error, timeout, 2xx without a valid SID unknown Never

Twilio documents that a 429 with error 20429 was not processed. A 429 without that code may come from a proxy, so SMS SDK treats it as unknown. error.provider.code holds Twilio’s error code and error.provider.requestId the Twilio-Request-Id header. For adapter authors, the subpath also exports buildTwilioForm, interpretTwilioResponse, twilioRejectionCategory, and twilioDelivery.

Official documentation

Checked on 2026-10-08. The full evidence list is in PROVIDERS.md.

The guide above also uses these, checked on 2026-10-28:

Next steps

Last updated on