Telnyx SMS API with TypeScript: send, verify, and test
Send SMS through the Telnyx API v2 from TypeScript, verify Ed25519 webhooks in Next.js, and test offline with signed fixtures, using fetch or SMS SDK.
This guide takes a TypeScript server from a Telnyx API key to a verified delivery event. You send one SMS with the raw Telnyx API v2, verify a signed webhook by hand, then build the same thing with the SMS SDK telnyx() adapter: a protected send route, a Next.js webhook route that drops duplicates, and tests that run offline. The second half of the page is the adapter reference. To compare providers first, see Choose a provider.
Everything here uses Telnyx API v2: https://api.telnyx.com/v2 with a Bearer API key. Older tutorials post to sms.telnyx.com with an x-profile-secret header; that is API v1 and does not apply.
Support status
Supported. Requests, responses, the error catalog, and webhook signing follow Telnyx’s official documentation and its official Node SDK, and the adapter passes the shared contract tests. Limits to know:
- No validity period. Telnyx’s send request has no expiry field, so
validityPeriodSecthrowsUnsupportedFieldError. - Alphanumeric senders need
messagingProfileIdon the adapter. - Webhooks are verified with a public key, not the API key. The URL is not signed.
- Webhook timestamps must be within 300 seconds of now by default.
Before you start
You need four things from the Telnyx portal (Mission Control):
- A number with SMS. Buy a number with the SMS feature, or use a short code or alphanumeric sender.
- A messaging profile. Create one under Messaging, then assign your number to it. A number that is not on a profile cannot send.
- An API v2 key. Create it under API Keys. It goes in an
Authorization: Bearerheader. - Your public key. Copy it from Keys & Credentials, Public Key. It verifies webhook signatures and is not secret, but it is not the API key either.
US traffic to mobile numbers also needs 10DLC registration for long codes, or verification for toll-free numbers. To try sending before registration, Telnyx suggests buying two Telnyx numbers and texting from one to the other. See Registration and consent.
The examples read these variables:
| Variable | Required | Used for |
|---|---|---|
TELNYX_API_KEY |
Yes | API v2 key, sent as a Bearer token. |
TELNYX_FROM |
Unless you send from a profile | Default sender in E.164, such as +15550100001. |
TELNYX_MESSAGING_PROFILE_ID |
For alphanumeric senders | Messaging profile ID sent with every message. |
TELNYX_PUBLIC_KEY |
For webhooks | Base64 Ed25519 public key. |
TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_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 API key on the server.
Send an SMS with the raw API v2
One POST /v2/messages request sends a message. It needs only fetch, which Node.js 18 and later have built in:
const apiKey = process.env.TELNYX_API_KEY;
if (apiKey === undefined || apiKey === "") throw new Error("Set TELNYX_API_KEY.");
const response = await fetch("https://api.telnyx.com/v2/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
from: "+15550100001",
to: "+14155550123",
text: "Your order has shipped.",
}),
});
const body: unknown = await response.json();
console.log(response.status, JSON.stringify(body, null, 2));
A successful send prints 200 and the new message. This copy is shortened, with example IDs:
{
"data": {
"record_type": "message",
"id": "40385f64-5717-4562-b3fc-2c963f66afa6",
"type": "SMS",
"from": { "phone_number": "+15550100001" },
"to": [{ "phone_number": "+14155550123", "status": "queued" }],
"text": "Your order has shipped.",
"parts": 1
}
}
Save data.id. Every later webhook about this message carries it as data.payload.id.
A 4xx with errors[0].code means Telnyx refused the message, and the code says why. A 5xx, a timeout, or a dropped connection means you don’t know whether Telnyx took it, so don’t send again blindly. Telnyx accepts an optional Idempotency-Key header for safe retries: reuse the same key only when you retry the same send. With that header, a 409 means a request with the key is still in progress: retry the same request with the same key. A 422 means the key was already used with a different body: resend the original body with that key. Neither says the first send failed, so never switch to a new key for the same message.
Accepted is not delivered
The 200 means Telnyx accepted and queued the message. Delivery to the phone is reported later, by webhook:
| Stage | Raw API | SMS SDK |
|---|---|---|
| Accepted | 200 with data.id, recipient status queued |
send() resolves with handoff: "accepted" and delivery: "queued" |
| Refused | 4xx with errors[0].code |
ProviderRejectedError with a category |
| Outcome unknown | 5xx, timeout, network error | HandoffUnknownError. Never resent automatically. |
| Handed to the carrier | message.sent webhook, status sent |
message.sent event |
| Delivered or failed | message.finalized webhook, status delivered, delivery_failed, sending_failed, or expired |
message.delivered, message.undelivered, or message.filtered event |
Verify a webhook with the raw API
Telnyx sends webhooks to the URL on the message (webhook_url) or, if there is none, the URL on the messaging profile. Each request has two headers: telnyx-signature-ed25519, a base64 Ed25519 signature, and telnyx-timestamp, Unix seconds. The signature covers ${timestamp}|${rawBody}, so you must check it against the exact bytes Telnyx sent, before you parse them:
export async function verifyTelnyxWebhook(request: Request, publicKey: string): Promise<unknown> {
const rawBody = await request.text();
const signature = request.headers.get("telnyx-signature-ed25519");
const timestamp = request.headers.get("telnyx-timestamp");
if (signature === null || timestamp === null) throw new Error("Missing Telnyx signature headers.");
const ageSec = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!(ageSec <= 300)) throw new Error("Telnyx timestamp is missing or too old.");
const fromBase64 = (value: string) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
const key = await crypto.subtle.importKey("raw", fromBase64(publicKey), { name: "Ed25519" }, false, ["verify"]);
const signed = new TextEncoder().encode(`${timestamp}|${rawBody}`);
if (!(await crypto.subtle.verify("Ed25519", key, fromBase64(signature), signed))) {
throw new Error("Invalid Telnyx signature.");
}
return JSON.parse(rawBody);
}
The function rejects requests without both headers, requests older than five minutes, and bodies that don’t match the signature. It returns the parsed JSON only after the check passes. You still have to map Telnyx’s statuses, drop duplicate deliveries, and detect STOP replies yourself, which is what the SMS SDK version below does.
Common setup errors
| What you see | Cause | Fix |
|---|---|---|
| 401, error 10009 | Missing or wrong API key, or an API v1 profile secret | Send an API v2 key as Authorization: Bearer <key>. |
| 400, error 40305 | Telnyx can’t use the from address: an invalid number or sender ID, or one not set up for messaging |
Check that from is a number or sender ID on your account, enabled for messaging and assigned to a messaging profile. |
| 400, error 40310 | The to number is not valid |
Send E.164, such as +14155550123. |
| 400, error 40300 | The recipient replied STOP | Don’t send to them until they reply START. |
200, but the text never arrives |
Acceptance is not delivery | Read message.finalized and its errors. Check 10DLC or toll-free registration. |
| No webhooks arrive | No URL on the message or the messaging profile | Set the profile’s webhook URL, or pass webhookUrl per message. |
invalid_signature |
The body was read or parsed before verification, or the key is wrong | Pass the untouched request; use the public key from Keys & Credentials. |
invalid_credentials |
The key is not 32 bytes of base64, often the API key by mistake | Use the Ed25519 public key. |
stale_timestamp |
Server clock drift, or a replayed request | Sync the clock; the window is 300 seconds. |
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 telnyx(), optionally falls back to Twilio when Telnyx proves it refused the message, stops on an unknown outcome, and verifies every webhook before it reads it.
npm install @opencoredev/sms-sdkpnpm add @opencoredev/sms-sdkyarn add @opencoredev/sms-sdkbun add @opencoredev/sms-sdknub add @opencoredev/sms-sdkaube add @opencoredev/sms-sdk1. Create the client and handlers
import {
AllProvidersRejectedError,
createSmsClient,
HandoffUnknownError,
isE164,
memoryIdempotencyStore,
PolicyRejectedError,
ProviderRejectedError,
type E164,
type SmsAdapter,
} 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 sender(name: string): E164 {
const value = env(name);
if (!isE164(value)) throw new Error(`${name} must be an E.164 number.`);
return value;
}
function twilioFallback(): SmsAdapter[] {
const { TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN } = process.env;
if (TWILIO_ACCOUNT_SID === undefined || TWILIO_AUTH_TOKEN === undefined) return [];
return [twilio({ accountSid: TWILIO_ACCOUNT_SID, authToken: TWILIO_AUTH_TOKEN, from: sender("TWILIO_FROM") })];
}
export const sms = createSmsClient({
adapters: [telnyx({ apiKey: env("TELNYX_API_KEY"), from: sender("TELNYX_FROM") }), ...twilioFallback()],
fallback: "on-known-rejection",
// Checked before any provider request, so 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() },
});
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(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 webhook 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) {
// The provider may have 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) 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 handleTelnyxWebhook(request: Request): Promise<Response> {
let event: SmsEvent;
try {
event = await parseSmsWebhook({ provider: "telnyx", request, credentials: { publicKey: env("TELNYX_PUBLIC_KEY") } });
} catch (error) {
if (error instanceof WebhookSignatureError) return new Response("Invalid signature", { status: 401 });
throw error;
}
// Record the event ID and its effects together, so a failed write rolls both back and Telnyx's retry is handled.
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 "message.received":
await tx.inbox.save({ from: event.from, to: event.to, body: event.body, providerId: event.providerId });
// A START reply arrives as message.received, not recipient.opted_in, so lift the suppression here.
if (event.body.trim().toUpperCase() === "START") await tx.suppressions.remove(event.from);
break;
}
});
return new Response(null, { status: 200 });
}
sendSms() returns one of three outcomes. accepted names the provider that took the message. rejected means no provider took it, either because the recipient opted out (checked by beforeSend before any request) or because the providers refused it. unknown means a timeout, network error, or 5xx left the result unclear; the message is flagged for review and not resent, even when Twilio is configured. A retry with the same idempotency key returns the stored result when the first send was accepted, and throws HandoffUnknownError again when its outcome was unknown, so neither case texts twice. After a rejection, the same key and payload may send again. memoryIdempotencyStore() forgets all of this when the process restarts. Before production, swap it for a durable store such as the Postgres store. Twilio is tried only after a Telnyx rejection that belongs to your Telnyx account, such as bad credentials or an unusable sender; see Fallback and retries.
handleTelnyxWebhook() answers 401 to forged requests, answers 200 to a repeat without handling it twice, records status, opt-out, and inbound events, and lifts the suppression when someone who opted out replies START. dedupeKey is the Telnyx event ID, so 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, the handler answers 500, and Telnyx’s retry gets processed. Events can arrive out of order, and a status event 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.
The routes below import this module as @/telnyx-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 API key can never reach a client bundle, and never prefix these variables with NEXT_PUBLIC_. If you configure Twilio, its status callbacks need their own route; see Twilio.
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 number flagged. 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 { sendSms } from "@/telnyx-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({
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 webhooks in Next.js
import { handleTelnyxWebhook } from "@/telnyx-sms";
export const runtime = "nodejs";
export async function POST(request: Request): Promise<Response> {
return handleTelnyxWebhook(request);
}
The route hands the untouched Request to the handler. Don’t call request.json() or request.text() first, and keep middleware from reading the body, because the signature covers the exact bytes and 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".
Set this route’s public HTTPS URL as the webhook URL on your messaging profile, or pass it per message as webhookUrl. Telnyx expects a 2xx within 2 seconds and retries otherwise, so store the event and return; do slow work later. To reach your laptop, expose the port with a tunnel; see Test without a provider.
4. Test it offline
These tests send nothing and need no Telnyx account. They replace fetch with canned Telnyx and Twilio responses, in order, and sign webhook fixtures with a key pair made for the test, so the real Ed25519 check runs:
import { expect, mock, spyOn, test } from "bun:test";
import { generateTelnyxKeyPair, signedTelnyxRequest } from "@opencoredev/sms-sdk/testing";
import { db } from "./db";
const { privateKey, publicKey } = await generateTelnyxKeyPair();
Object.assign(process.env, {
TELNYX_API_KEY: "KEY_test",
TELNYX_FROM: "+15550100001",
TELNYX_PUBLIC_KEY: publicKey,
TWILIO_ACCOUNT_SID: "AC0123456789abcdef0123456789abcdef",
TWILIO_AUTH_TOKEN: "test",
TWILIO_FROM: "+15550100002",
});
// `server-only` throws outside a Next.js server build, so stub it before loading the module.
mock.module("server-only", () => ({}));
const { handleTelnyxWebhook, sendSms } = await import("./telnyx-sms");
function fakeFetch(...replies: Response[]) {
const fetch = spyOn(globalThis, "fetch").mockRejectedValue(new Error("Unexpected network call"));
for (const reply of replies) fetch.mockResolvedValueOnce(reply);
return fetch;
}
test("Telnyx accepts the message", async () => {
const fetch = fakeFetch(Response.json({ data: { id: "msg_1", to: [{ phone_number: "+14155550123", status: "queued" }] } }));
const outcome = await sendSms({ to: "+14155550123", body: "Order 1 has shipped.", idempotencyKey: "order:1:shipped" });
expect(outcome).toEqual({ kind: "accepted", provider: "telnyx", providerId: "msg_1" });
expect(fetch).toHaveBeenCalledTimes(1);
fetch.mockRestore();
});
test("a Telnyx sender rejection falls back to Twilio", async () => {
const fetch = fakeFetch(
Response.json({ errors: [{ code: "40305", title: "Invalid 'from' address" }] }, { status: 400 }),
Response.json({ sid: "SM0123456789abcdef0123456789abcdef", status: "queued" }, { status: 201 }),
);
const outcome = await sendSms({ to: "+14155550123", body: "Order 2 has shipped.", idempotencyKey: "order:2:shipped" });
expect(outcome).toEqual({ kind: "accepted", provider: "twilio", providerId: "SM0123456789abcdef0123456789abcdef" });
expect(fetch).toHaveBeenCalledTimes(2);
fetch.mockRestore();
});
test("an unknown outcome stops without trying Twilio", async () => {
const fetch = fakeFetch(new Response("Service Unavailable", { status: 503 }));
const outcome = await sendSms({ to: "+14155550123", body: "Order 3 has shipped.", idempotencyKey: "order:3:shipped" });
expect(outcome).toEqual({ kind: "unknown" });
expect(fetch).toHaveBeenCalledTimes(1);
fetch.mockRestore();
});
const delivered = {
data: {
id: `evt_${crypto.randomUUID()}`,
event_type: "message.finalized",
payload: { id: "msg_1", to: [{ phone_number: "+14155550123", status: "delivered" }] },
},
};
const url = "https://example.com/api/webhooks/telnyx";
test("a signed delivery event is recorded once", async () => {
const updateStatus = spyOn(db.messages, "updateStatus");
const first = await handleTelnyxWebhook(await signedTelnyxRequest({ privateKey, url, body: delivered }));
const repeat = await handleTelnyxWebhook(await signedTelnyxRequest({ privateKey, url, body: delivered }));
expect([first.status, repeat.status]).toEqual([200, 200]);
expect(updateStatus).toHaveBeenCalledTimes(1);
expect(updateStatus).toHaveBeenCalledWith("msg_1", "message.delivered", undefined);
});
test("a forged event is refused", async () => {
const other = await generateTelnyxKeyPair();
const forged = await signedTelnyxRequest({ privateKey: other.privateKey, url, body: delivered });
expect((await handleTelnyxWebhook(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:
telnyx-sms.test.ts:
(pass) Telnyx accepts the message [5.58ms]
(pass) a Telnyx sender rejection falls back to Twilio [1.13ms]
(pass) an unknown outcome stops without trying Twilio [0.46ms]
(pass) a signed delivery event is recorded once [1.76ms]
(pass) a forged event is refused [0.52ms]
5 pass
0 fail
10 expect() calls
Ran 5 tests across 1 file. [23.00ms]
Before the first live send, npx @opencoredev/sms-sdk doctor --adapter telnyx checks your variables and sender without sending anything. See Doctor CLI.
Adapter options
import { createSmsClient } from "@opencoredev/sms-sdk";
import { telnyx } from "@opencoredev/sms-sdk/telnyx";
const sms = createSmsClient({
adapters: [
telnyx({
apiKey: process.env.TELNYX_API_KEY ?? "",
from: "+15550100001",
// Needed only for alphanumeric senders:
// messagingProfileId: process.env.TELNYX_MESSAGING_PROFILE_ID,
}),
],
});
const result = await sms.send({ to: "+14155550123", body: "Your order has shipped." });
console.log(result.providerId); // the Telnyx message ID (data.id)
telnyx() throws ConfigurationError at startup when apiKey is empty. Two more options exist for tests and proxies: baseUrl (default https://api.telnyx.com) and fetch.
The adapter calls POST /v2/messages with a JSON body. Delivery comes from data.to[0].status, usually queued. A 2xx without data.id 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, plus messaging_profile_id from the adapter |
| Messaging profile number pool | { messagingService: "<profile id>" } |
messaging_profile_id, with no from |
An alphanumeric sender without messagingProfileId on the adapter fails local validation before any request. In Telnyx, assign each number to a messaging profile before it sends.
US A2P traffic to mobile numbers needs 10DLC registration, toll-free numbers need verification, and a short code works in one country only. Alphanumeric senders can’t reach the US, Canada, or Puerto Rico, and recipients can’t reply to them. Some countries, such as the UK and France, require sender ID registration in advance. Telnyx’s sender type guide covers the rules. SMS SDK does not check them before sending; see Registration and consent.
Features
| Feature | Telnyx |
|---|---|
| MMS | Yes, sent with type: "MMS" |
Scheduling (sendAt) |
Yes, from any sender |
| Validity period | No |
Per-message webhookUrl |
Yes, sent as webhook_url |
Provider options
Pass other POST /v2/messages fields in providerOptions.telnyx:
import { sms } from "./sms";
await sms.send({
to: "+14155550123",
body: "Your order has shipped.",
webhookUrl: "https://example.com/webhooks/sms/telnyx",
providerOptions: {
telnyx: { encoding: "gsm7", webhookFailoverUrl: "https://backup.example.com/webhooks/sms/telnyx" },
},
});
| Option | Telnyx field | Type |
|---|---|---|
subject |
subject |
string, the subject of an MMS |
webhookFailoverUrl |
webhook_failover_url |
http or https URL |
useProfileWebhooks |
use_profile_webhooks |
boolean, Telnyx default true |
autoDetect |
auto_detect |
boolean, Telnyx default false |
encoding |
encoding |
"auto" | "gsm7" | "ucs2". With "gsm7", Telnyx answers 400 if a character has no GSM-7 form. |
extra |
any other field | 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 telnyx adapter sends. extra cannot set the fields SMS SDK owns: to, from, messaging_profile_id, text, media_urls, type, webhook_url, and send_at. 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: your account’s Ed25519 public key. A key that is not 32 bytes of base64 fails with
invalid_credentials. - Point Telnyx at it: for status, pass
webhookUrlper message or set the webhook URL on the messaging profile. For inbound, set the inbound webhook URL on the profile the number belongs to. - Signing:
telnyx-signature-ed25519covers`${telnyx-timestamp}|${rawBody}`. The URL is not signed, so proxies don’t affect verification and there is nopublicUrloption. - Replay window: 300 seconds either side of now by default. Older or future timestamps fail with
stale_timestamp. Change it withtoleranceSec.
SMS SDK reads message.received, message.sent, and message.finalized events. Status comes from data.payload.to[0].status:
| Telnyx status | Event |
|---|---|
queued, sending |
message.queued |
sent, delivery_unconfirmed |
message.sent |
delivered |
message.delivered |
sending_failed, delivery_failed, expired |
message.undelivered, or message.filtered with error 40002, 40003, or 40322 |
Other events and statuses, such as read |
unrecognized |
message.received |
message.received, or a recipient.* event from STOP and HELP keywords (source: "keyword") |
Telnyx sends no opt-out flag, so opt-outs come from keyword detection. dedupeKey is telnyx:{data.id}, the webhook event ID. providerId is the message ID, data.payload.id, which matches result.providerId.
Limitations
- No
validityPeriodSec. For an expiry, use Twilio, Plivo, Vonage, or Sinch. - Error 40008 is not mapped to
message.filtered, because Telnyx’s pages disagree on its meaning. It staysmessage.undelivered.
Error codes
The code comes from errors[0].code in the response.
| Telnyx response | Category | Falls back |
|---|---|---|
| 10009, 10010, 20001, 20002, 20003, 20006, 20008; 401 or 403 without a listed code | auth |
Yes |
| 10011, 40318 (queue full) | rate_limited |
Yes, after retries |
| 40305, 40306, 40308, 40315, 40320, 40321, 40329, 40330 | sender |
Yes |
| 20013, 20100, 40309, 40312, 40314, 40331, 40333 (spend limit) | account |
Yes |
| 40301, 40310, 40319 | recipient |
No |
| 40300 (blocked due to STOP), 40322 (blocked content) | compliance |
Never |
| Any other 4xx | request |
No |
| 429 without code 10011 or 40318 | unknown | Never |
5xx, network error, timeout, 2xx without data.id |
unknown | Never |
Telnyx does not document a Retry-After header, but SMS SDK honors one on a rate limit. error.provider.requestId holds the x-request-id header. For adapter authors, the subpath also exports buildTelnyxRequest, interpretTelnyxResponse, telnyxRejectionCategory, and telnyxDelivery.
Official documentation
Checked on 2026-10-08. The full evidence list is in PROVIDERS.md.
- Send a message
- Receiving messaging webhooks
- Webhook delivery and signing
- API errors
- Alphanumeric sender ID
- International SMS compliance
- Official Node SDK webhook verification
Next steps
Related
- How to send SMS through an API in TypeScript: the raw send request for six providers side by side, then the same send with SMS SDK.
- SMS fallback without double-texting: when a second provider should take a text, and why a timeout means stop.
- Twilio alternatives for developers: what moves when you switch providers, and when to stay on Twilio.