Quick start
Send your first SMS through Twilio with SMS SDK in three steps, then send from a Hono or Bun server route.
By the end of this page, a server-side script sends one SMS through Twilio and prints the provider’s message ID.
- Using another provider? Swap in the adapter from its provider page.
- No provider account yet? Try the API with
memory(), a test adapter that sends nothing. A real text always needs an account with Twilio or another supported provider, because SMS SDK calls your provider’s API. It is not a carrier.
You need a Twilio Account SID, Auth Token, and a Twilio number that can text your phone. Registering that number for 10DLC or toll-free is up to you. See Registration and consent.
1. Install
npm install @opencoredev/sms-sdkpnpm add @opencoredev/sms-sdkyarn add @opencoredev/sms-sdkbun add @opencoredev/sms-sdknub add @opencoredev/sms-sdkaube add @opencoredev/sms-sdkThe examples on this page are TypeScript, and SMS SDK is ESM only, so your project has to load its files as ES modules. Bun runs them as they are. On Node.js, add tsx to run TypeScript and set "type": "module" in package.json:
npm install --save-dev tsx
npm pkg set type=module
Without it, tsx loads .ts files as CommonJS, and the top-level await in send.ts fails.
2. Create the client
Put your credentials in .env on your server. Never send them to a browser.
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_FROM=+15550100001
Create the client in its own module so the rest of your app imports one instance:
import { createSmsClient, isE164 } from "@opencoredev/sms-sdk";
import { twilio } from "@opencoredev/sms-sdk/twilio";
const from = process.env.TWILIO_FROM;
if (!isE164(from)) {
throw new Error("Set TWILIO_FROM to your Twilio number in E.164 format, such as +15550100001.");
}
export const sms = createSmsClient({
adapters: [
twilio({
accountSid: process.env.TWILIO_ACCOUNT_SID ?? "",
authToken: process.env.TWILIO_AUTH_TOKEN ?? "",
from,
}),
],
});
Creating the client makes no network request. A malformed Account SID or empty Auth Token makes twilio() throw a ConfigurationError at startup, not on the first send.
3. Send a message
import { isSmsError } from "@opencoredev/sms-sdk";
import { sms } from "./sms";
try {
const result = await sms.send({
to: "+14155550123", // replace with your own phone number
body: "Hello from SMS SDK.",
idempotencyKey: "quick-start:1",
});
console.log(`Accepted by ${result.provider}: ${result.providerId} (${result.delivery})`);
} catch (error) {
if (isSmsError(error)) {
console.error(error.code, error.message, `retrySafe: ${error.retrySafe}`);
}
throw error;
}
Run it with npx tsx --env-file=.env send.ts on Node.js 20.6 or newer (the first version with --env-file), or bun send.ts on Bun, which loads .env itself. It prints a line like Accepted by twilio: SM… (queued).
If the send fails, read the error’s code and retrySafe. provider_auth means Twilio rejected your credentials. handoff_unknown means SMS SDK cannot tell whether Twilio took the message, so check the Twilio console before you send again. Errors lists every code.
4. Receive a delivery update
queued means Twilio accepted the message, not that the phone got it. Twilio reports delivery later by calling a webhook URL on your server. Store result.providerId so you can match the update to the message, then follow Webhooks to verify and read it.
Try it without a provider account
The memory() adapter from @opencoredev/sms-sdk/testing records each send and returns a fake message ID. It makes no network request, so no text is sent and nothing reaches a phone. This script needs the install from step 1, including tsx and "type": "module" on Node.js, but no credentials and no .env:
import { createSmsClient } from "@opencoredev/sms-sdk";
import { memory } from "@opencoredev/sms-sdk/testing";
const adapter = memory();
const sms = createSmsClient({ adapters: [adapter] });
const result = await sms.send({ to: "+14155550123", body: "Hello from SMS SDK." });
console.log(`Accepted by ${result.provider}: ${result.providerId} (${result.delivery})`);
for (const sent of adapter.sent) console.log(`Recorded: ${sent.message.to} "${sent.message.body}"`);
Run it with npx tsx try-memory.ts or bun try-memory.ts. It prints:
Accepted by memory: memory_1 (queued)
Recorded: +14155550123 "Hello from SMS SDK."
To send for real, go back to steps 2 and 3: the client in sms.ts uses twilio() and your credentials. To use memory() in a test suite, see Test without a provider.
Send from a Hono or Bun server
To send an SMS from a Hono or Bun server, import the client from sms.ts and call sms.send() inside a POST route that checks who is calling and picks the recipient on the server. SMS SDK has no runtime dependencies and calls providers with fetch, so one handler that takes a Request and returns a Response works in Hono, Bun.serve, and Next.js route handlers.
import { HandoffUnknownError, isE164, isSmsError } from "@opencoredev/sms-sdk";
import { getSession } from "./auth";
import { db } from "./db";
import { sms } from "./sms";
export async function handleSend(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 });
// Look the number up yourself. Taking `to` from the request body turns the route into an open SMS relay.
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 });
try {
const result = await sms.send({
to: order.phone,
body: `Order ${order.id} has shipped.`,
idempotencyKey: `order:${order.id}:shipped`,
});
return Response.json({ providerId: result.providerId, delivery: result.delivery });
} catch (error) {
// The provider may have the message. Don't send it again automatically.
if (error instanceof HandoffUnknownError) return Response.json({ status: "unknown" }, { status: 202 });
if (isSmsError(error)) return Response.json({ code: error.code }, { status: 422 });
throw error;
}
}
Mount it in Hono, after npm install hono:
import { Hono } from "hono";
import { handleSend } from "./send-route";
const app = new Hono();
app.post("/api/orders/notify", (c) => handleSend(c.req.raw));
export default app;
Or in Bun.serve, with no framework:
import { handleSend } from "./send-route";
Bun.serve({
port: 3000,
routes: {
"/api/orders/notify": { POST: handleSend },
},
fetch: () => new Response("Not found", { status: 404 }),
});
Bun reads .env on its own, so bun server.ts starts either one with your Twilio credentials. Hono on Node.js needs its Node adapter, @hono/node-server. In a running server, the idempotencyKey only stops a repeated request from sending twice once the client has an idempotency store; see Prevent duplicate sends. The Twilio guide adds webhook routes and offline tests to this setup, and Receive webhooks shows the Hono and Bun.serve handlers for delivery updates.
Next steps
- How sending works: the three outcomes and what the client does by default.
- Fallback and retries: add a second provider safely.
- How to send SMS through an API in TypeScript (blog): the raw HTTP request for six providers, and a protected send route.
- Message length and cost: how many characters fit in one segment, and why one emoji can double the count.
- Handle STOP and HELP replies: keep opted-out numbers off your send list across providers.
- Switch SMS providers: move from Twilio to Telnyx or another provider: swap the adapter, set up the new sender and webhooks, and carry over opt-outs.