← Back to dashboard

Twilio Integration Guide

What is Twilio?

The real model

API-key client, Messaging Service sends, Verify for OTP, and validateRequest on every inbound hit.

Authenticate REST with twilio(apiKeySid, apiKeySecret, { accountSid }) and keep the Auth Token only for X-Twilio-Signature checks: validateRequest(token, sig, publicUrl, params) for form webhooks, validateRequestWithBody for JSON. Behind Vercel, rebuild the public URL. Send via messagingServiceSid so the A2P Campaign applies, and register before launch (Campaign vetting is $15 and takes ~5 business days). Verify costs $0.05 per successful check plus channel fees. A wrong code returns 'pending', and an expired or spent verification throws 404. ConversationRelay is $0.07/min plus voice minutes. Validate the wss handshake signature and stream tokens with last:true at the end. WhatsApp outside 24h needs contentSid templates. Agents can query the hosted docs MCP at mcp.twilio.com/docs. For Kenya-targeted projects, use Africa's Talking: Twilio is $0.3134 per segment there vs KES 0.4–0.8.

Five Twilio primitives

Messaging is the core; registration decides whether it gets delivered in the US.

Text
████████╗██╗    ██╗██╗██╗     ██╗ ██████╗
╚══██╔══╝██║    ██║██║██║     ██║██╔═══██╗
   ██║   ██║ █╗ ██║██║██║     ██║██║   ██║
   ██║   ██║███╗██║██║██║     ██║██║   ██║
   ██║   ╚███╔███╔╝██║███████╗██║╚██████╔╝
   ╚═╝    ╚══╝╚══╝ ╚═╝╚══════╝╚═╝ ╚═════╝

Twilio Integration Guide

Focus: When and how codeAmani uses Twilio for US/global communications: Programmable Messaging (SMS/MMS) and the US registration rules that gate it (A2P 10DLC, toll-free verification), the managed Verify API for OTP, Lookup for phone intelligence, Voice and ConversationRelay voice AI agents, secure inbound webhooks with X-Twilio-Signature, WhatsApp via Twilio, and the official Twilio MCP server. For Kenya-targeted projects the default is Africa's Talking (see Kenya: Twilio vs Africa's Talking).

Overview

Twilio is a REST cloud-communications platform with an official twilio Node.js helper library (v6.2.0, released 2026-10-12, Node.js >= 20). The SDK exposes the whole platform: client.messages (SMS/MMS/WhatsApp/RCS), client.verify.v2 (OTP), client.lookups.v2 (phone intelligence), client.calls (Voice), and TwiML builders (twilio.twiml.VoiceResponse, MessagingResponse). SMS and WhatsApp share one messages.create call; only the address format changes (+1555… vs whatsapp:+1555…).

What changed since the last review (2026-08-23):

AreaNow
SDKtwilio 6.2.0: signature comparison moved from the deprecated scmp package to crypto.timingSafeEqual; TwiML <Stream> gains audioFormat/sampleRate. No API breaks.
CLItwilio-cli 7.2.0. The 7.x line requires Node.js >= 22 (the SDK still runs on 20).
MCPTwilio now runs an official hosted MCP server at https://mcp.twilio.com/docs (Public Beta, read-only, no auth). The old guide said there was none.
US complianceUnregistered 10DLC traffic is blocked (30034). Unverified or pending toll-free traffic is blocked (30032). Every new 10DLC Campaign pays a $15 vetting fee and waits up to ~5 business days.
Voice AIConversationRelay (<Connect><ConversationRelay>) is the documented path for LLM voice agents at $0.07/min plus normal voice minutes.
WhatsAppSince 2025-04-01, templates sent outside the 24-hour window must use contentSid + contentVariables. A template sent in body fails with 63016.

The canonical OTP flow. Verify holds the code, so your app never stores or compares it:

Check first. Before adding Twilio to a build, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm the audience. Kenya-targeted → Africa's Talking. US / global, Voice, voice AI, or managed OTP → Twilio. Choosing the wrong provider means worse delivery and higher per-message cost.

Official Documentation

Twilio MCP server (official, Public Beta)

Twilio hosts a read-only docs/API-spec MCP server at https://mcp.twilio.com/docs. It needs no account or key. It exposes two tools: twilio__search (natural-language search over 1,800+ endpoints, docs, and support articles) and twilio__retrieve (full parameter and response schemas for the IDs that search returns). It does not execute API calls. Twilio says execute-capable OAuth tools are planned.

Bash
claude mcp add --transport http twilio-docs https://mcp.twilio.com/docs

It is also packaged in the twilio-developer-kit Claude Code/Cursor plugin, together with "Twilio Skills". By default it returns the latest API version. Programmable Messaging has a v2010 surface (the one client.messages.create calls) and a newer v1 (comms.twilio.com, Bulk Messaging). Filter by version when you need v2010.

The older community package @twilio-alpha/mcp (0.7.0, last published July 2025) wraps the live APIs with your credentials. It is an alpha package that hasn't been updated since, so don't use it in codeAmani builds. Use the hosted docs server for lookups and the SDK for execution.


1. Credentials & install

The console gives you the Account SID (AC…) and Auth Token. For server code, prefer an API Key (SK… SID + secret, created under Account > API keys) over the Auth Token. API keys can be revoked one at a time. You still need the Auth Token to validate webhook signatures, because Twilio signs with it.

Bash
npm install twilio@6.2.0   # Node.js >= 20 (engines field)
TypeScript
// lib/twilio.ts — server-only module
import twilio from "twilio";

const accountSid = process.env.TWILIO_ACCOUNT_SID!;

// API key auth (preferred): revocable, scoped, no full-account token in the REST path.
export const client = twilio(process.env.TWILIO_API_KEY_SID!, process.env.TWILIO_API_KEY_SECRET!, {
  accountSid,
});

// Auth Token is still required for X-Twilio-Signature validation.
export const authToken = process.env.TWILIO_AUTH_TOKEN!;

Phone numbers must be E.164 (+15619991234, +254711223344). Twilio always wants the leading +. The Auth Token is a full-account secret: keep it server-side, never import lib/twilio.ts into a client component, and list the variable in ENV_MASTER.md.

2. US sending rules (read before the first SMS)

US carriers treat all Twilio traffic as application-to-person (A2P). Volume doesn't matter: hobby and test traffic counts too. Pick a sender type and register it before launch. Registration takes days.

SenderWhat you must doBlocked if skippedThroughput / notes
10DLC long code (+1 local)A2P 10DLC Brand + Campaign in Trust Hub, number in the Campaign's Messaging Service sender poolYes, error 30034Campaign vetting up to ~5 business days. Sole Prop: 1 number per campaign.
Toll-free (8XX)Toll-free verification (business, use case, opt-in proof, samples)Yes, error 30032 (Restricted/Pending)Explicit opt-in evidence is always required (30515). Use branded HTTPS URLs, not public shorteners (30449).
Short codeCarrier short-code application (weeks)n/aHighest throughput. $1,000–$1,500/quarter lease.
Verify (OTP only)Nothing extra: Verify uses Twilio's pre-registered sendersNoUse it if you only need OTP and don't want to register 10DLC.

A2P 10DLC registration fees (TCR pass-through, help.twilio.com/articles/1260803965530, fees updated 2025-08-01):

FeeSole ProprietorLow-Volume StandardStandard
Brand registration (one-time)$4.50$4.50$4.50
Secondary vetting (one-time)——$41.50
Campaign vetting (one-time, non-refundable)$15$15$15
Campaign monthly$2$1.50 (low-volume mixed) – $10$1.50 – $10

Special campaign types cost $3/mo (charity / 501(c)(3)) and $5/mo (emergency). Use the charity rate for the codeAmani 501(c)(3) donation portal. Low-Volume Standard brands are for fewer than 6,000 messages/day. Low-volume mixed campaigns cap at 2,000 segments/day on T-Mobile.

3. Send an SMS (Programmable Messaging)

TypeScript
import { client } from "@/lib/twilio";

export async function sendSms(to: string, body: string): Promise<string> {
  const message = await client.messages.create({
    to, // E.164
    messagingServiceSid: process.env.TWILIO_MESSAGING_SERVICE_SID!, // "MG…", holds the registered sender pool
    body,
    statusCallback: "https://app.example.com/api/twilio/status", // queued → sent → delivered | undelivered | failed
  });
  return message.sid; // "SM…" means accepted for sending, not delivered
}

Send through a Messaging Service, not a bare from number. The service is what carries your A2P Campaign association, sender pool, opt-out handling, and Link Shortening.

  • MMS: add mediaUrl: ["https://…/file.png"] (US/Canada, up to 5 MB). Billed per message, not per segment.
  • Segments: SMS bills per 160-char GSM-7 segment (70 for UCS-2). One emoji switches the whole message to UCS-2.
  • Delivery: status on create is queued/accepted. Real delivery arrives on statusCallback. Watch errorCode: 30007 carrier filtering, 30034 unregistered 10DLC, 30032 unverified toll-free, 21610 recipient replied STOP.
  • Failed fee: $0.001 per message that ends in failed.

4. OTP / phone verification: the Verify API (preferred)

Don't roll your own OTP. Generating, storing, expiring, and rate-limiting codes is easy to get wrong. Verify v2 manages code generation, delivery over pre-registered senders, expiry, retries, translations, and Fraud Guard (SMS-pumping protection). You only call start and check.

TypeScript
// lib/verify.ts
import { client } from "@/lib/twilio";

const SERVICE = process.env.TWILIO_VERIFY_SERVICE_SID!; // "VA…"

export type VerifyChannel = "sms" | "call" | "whatsapp" | "email";

/** Start: send a code. */
export async function startVerification(to: string, channel: VerifyChannel = "sms"): Promise<string> {
  const v = await client.verify.v2.services(SERVICE).verifications.create({ to, channel });
  return v.status; // "pending"
}

/** Check: only "approved" means verified. */
export async function checkVerification(to: string, code: string): Promise<boolean> {
  const check = await client.verify.v2.services(SERVICE).verificationChecks.create({ to, code });
  return check.status === "approved"; // else: pending | canceled | max_attempts_reached | failed | expired
}

The full Next.js route pair is in examples/verify-routes.ts.

Gotcha: a wrong code returns status: "pending" (or max_attempts_reached). It doesn't throw. Only "approved" means verified. A verification expires after 10 minutes, and Twilio deletes it once it is approved, expired, or out of attempts. Any later check throws a RestException with HTTP 404, so catch that and start a new verification. Rate-limit the start route by IP and phone on your side too.

Pricing: $0.05 per successful verification plus channel fees. SMS adds $0.0083 per US SMS, charged on every attempt. Voice and email add nothing beyond the $0.05. Failed or expired verifications are not charged the $0.05, but SMS/voice delivery attempts still bill. Fraud Guard and translations into 42 languages are included.

5. Lookup v2: check a number before you text it

client.lookups.v2.phoneNumbers(n).fetch() with no fields is a free format check: valid, nationalFormat, countryCode. Paid data packages go in fields: line_type_intelligence (mobile / landline / VoIP / toll-free + carrier), sms_pumping_risk, sim_swap, caller_name, reassigned_number, and others.

TypeScript
const result = await client.lookups.v2
  .phoneNumbers("+15619991234")
  .fetch({ fields: "line_type_intelligence" });

if (!result.valid) throw new Error("Invalid number");
const lineType = (result.lineTypeIntelligence as { type?: string } | null)?.type; // "mobile" | "landline" | "nonFixedVoip" | …

Use it to drop landlines from SMS lists and to flag non-fixed VoIP on signup (a common fraud signal). Canadian numbers need NPAC approval, otherwise you get error 60601.

6. Voice and ConversationRelay (voice AI agents)

Outbound calls use TwiML, either inline twiml or a URL that returns it:

TypeScript
const call = await client.calls.create({
  to: "+15619991234",
  from: process.env.TWILIO_PHONE_NUMBER!,
  twiml: '<Response><Say voice="Polly.Joanna">This is a codeAmani appointment reminder.</Say></Response>',
});

ConversationRelay is Twilio's managed voice AI layer. Twilio runs speech-to-text and text-to-speech, and your WebSocket server only exchanges text with your LLM. Point the call at it with TwiML:

TypeScript
import twilio from "twilio";

const vr = new twilio.twiml.VoiceResponse();
const connect = vr.connect({ action: "https://app.example.com/api/twilio/voice/after-relay" });
connect.conversationRelay({
  url: "wss://agent.example.com/relay", // must be wss://
  welcomeGreeting: "Hi, this is the codeAmani assistant. How can I help?",
  ttsProvider: "ElevenLabs",
  transcriptionProvider: "Deepgram",
  interruptible: "any",
  dtmfDetection: true,
});
// return vr.toString() with Content-Type: text/xml

WebSocket protocol (JSON):

From TwilioMeaning
setupSent once on connect: callSid, from, to, customParameters
promptCaller speech: voicePrompt, lang, last
interruptCaller talked over TTS: utteranceUntilInterrupt
dtmfKeypress (only with dtmfDetection)
errorSession error
To TwilioMeaning
{ type: "text", token, last }Stream LLM tokens as they arrive. Set last: true on the final token. Don't trim tokens.
{ type: "end" }Hang up the relay, then the <Connect action> URL runs

Security: the WebSocket handshake carries X-Twilio-Signature. Validate it with validateRequest(authToken, signature, "wss://agent.example.com/relay", {}) before accepting the upgrade. A full server is in examples/conversation-relay-server.mts.

Before first use: accept the Predictive and Generative AI/ML Features Addendum under Console > Voice > Settings > Privacy & Security. Without it, ConversationRelay calls fail.

Pricing (US, Aug 2026): ConversationRelay $0.07/min, on top of voice minutes: local outbound $0.0140/min, inbound $0.0085/min, toll-free inbound $0.0220/min. Your LLM cost is separate. Route it per AI policy (Claude primary).

reportInputDuringAgentSpeech now defaults to none (it was any before May 2025). Set it explicitly if your agent relied on barge-in prompts.

7. Secure inbound webhooks (signature validation): required

Every inbound Twilio request (incoming SMS, status callbacks, voice webhooks, the ConversationRelay handshake) hits a public URL. Authenticate it. Twilio signs each request with your Auth Token and sends the result in X-Twilio-Signature:

  • Form-encoded body (the default for SMS/voice webhooks): twilio.validateRequest(authToken, signature, url, params). Argument order is token, signature, URL, params.
  • JSON body: twilio.validateRequestWithBody(authToken, signature, url, rawBody). The URL then carries a bodySHA256 query param.
TypeScript
// app/api/twilio/inbound/route.ts — Next.js App Router (Twilio POSTs application/x-www-form-urlencoded)
import twilio from "twilio";

export async function POST(req: Request): Promise<Response> {
  const signature = req.headers.get("x-twilio-signature") ?? "";
  const form = await req.formData();
  const params: Record<string, string> = {};
  for (const [k, v] of form.entries()) params[k] = String(v);

  // Twilio signs the PUBLIC URL it called. Behind Vercel/Cloudflare, req.url can be the
  // internal origin, so rebuild it from forwarded headers (or pin it via TWILIO_WEBHOOK_BASE_URL).
  const host = req.headers.get("x-forwarded-host") ?? req.headers.get("host");
  const url = `https://${host}/api/twilio/inbound`;

  if (!twilio.validateRequest(process.env.TWILIO_AUTH_TOKEN!, signature, url, params)) {
    return new Response("Invalid signature", { status: 403 });
  }

  // params.From / params.Body are untrusted input: sanitize before storing or rendering.
  const reply = new twilio.twiml.MessagingResponse();
  reply.message("Thanks, we got it.");
  return new Response(reply.toString(), { headers: { "Content-Type": "text/xml" } });
}

On Express, twilio.webhook() reads TWILIO_AUTH_TOKEN, validates, and returns 403 on failure. Mount express.urlencoded({ extended: false }) before it.

Gotcha: the signed URL must match byte-for-byte, including scheme, host, path, and query string. Behind a proxy, rebuild the public URL. An unparsed body produces empty params and a guaranteed mismatch. Pass every received parameter, not a hand-picked list: Twilio adds new parameters without notice. If you rotate the Auth Token, validation uses the primary token, so update TWILIO_AUTH_TOKEN everywhere when you promote the secondary.

8. WhatsApp via Twilio

Use the same messages.create with both addresses prefixed whatsapp:. Use the Sandbox for dev. Production needs a registered WhatsApp sender (Self Sign-up) and approved Content Templates.

TypeScript
// Inside the 24-hour customer-service window: free-form body is fine.
await client.messages.create({
  to: "whatsapp:+15619991234",
  from: process.env.TWILIO_WHATSAPP_FROM!, // "whatsapp:+1…"
  body: "Your codeAmani appointment is confirmed.",
});

// Outside the window (business-initiated): approved template by Content SID (HX…).
await client.messages.create({
  to: "whatsapp:+15619991234",
  from: process.env.TWILIO_WHATSAPP_FROM!,
  contentSid: "HXxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  contentVariables: JSON.stringify({ 1: "Amina", 2: "Tue 10:00" }),
});

Since 2025-04-01, a template sent as body outside the window fails with 63016. Use contentSid and remove body/mediaUrl. A2P 10DLC doesn't apply to WhatsApp. Meta's template fees are billed on top of Twilio's per-message fee. For template-heavy or Kenya-targeted WhatsApp (where the Meta Cloud API is often cheaper), see the whatsapp-business-api guide.

9. Kenya: Twilio vs Africa's Talking

For Kenya-targeted projects, use Africa's Talking for SMS. These are list prices pulled 2026-10-20:

Twilio → KenyaAfrica's Talking (Kenya)
Outbound SMS$0.3134 / segment (international routes)KES 0.8 → 0.4 / SMS on Safaricom by volume tier (Airtel and others KES 0.8 → 0.6), +16% VAT
Local numbersNone: domestic and international long codes and short codes are not supportedDedicated and shared short codes (KES 15,000/mo or KES 2,000/mo)
Sender IDAlphanumeric pre-registration (certificate of incorporation). Domestic registrations are not supported, and Safaricom requires registration for coverageLocal sender ID / short code provisioning
Two-way SMSNo (alphanumeric senders are one-way)Yes (short codes)
Extras—USSD, airtime, M-Pesa adjacency

At roughly 130 KES/USD, one Twilio segment to Kenya costs about 40 KES, around 50–100× the AT price. Use Twilio for Kenya only for Verify OTP to a few international users, or when a US product occasionally texts a Kenyan number. Payments in Kenya-targeted projects still go through M-Pesa (Daraja). Twilio has no part in that flow.


Environment Variables

Secrets (store in the vault / .env.local / Vercel env; never NEXT_PUBLIC_):

Bash
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_API_KEY_SECRET=your_api_key_secret_here

Non-secret identifiers and settings (config or .env.local, fine to log):

VariableExamplePurpose
TWILIO_ACCOUNT_SIDAC… (34 chars)Account identifier
TWILIO_API_KEY_SIDSK…API key identifier, paired with the secret
TWILIO_MESSAGING_SERVICE_SIDMG…Sender pool + A2P Campaign association
TWILIO_VERIFY_SERVICE_SIDVA…One Verify Service per environment
TWILIO_PHONE_NUMBER+15619991234Voice caller ID / single sender
TWILIO_WHATSAPP_FROMwhatsapp:+1…WhatsApp sender
TWILIO_WEBHOOK_BASE_URLhttps://app.example.comPublic base URL used to rebuild signed URLs behind proxies

Use separate Verify Services and Messaging Services per environment so dev traffic and rate limits stay isolated. Mirror these names in ENV_MASTER.md and each project's .env.example.

CLI Integration (optional)

Bash
npm install -g twilio-cli          # 7.2.0, requires Node.js >= 22
twilio login                       # stores a profile (API key) locally
twilio api:core:messages:create --from "+15619991234" --to "+15559876543" --body "Hello from codeAmani"
twilio phone-numbers:list
twilio api:lookups:v2:phone-numbers:fetch --phone-number "+15619991234" --fields line_type_intelligence

For local webhook testing, tunnel your dev server (ngrok http 3000) and set the HTTPS URL as the number's or Messaging Service's webhook. Validate signatures against the ngrok URL. More commands are in reference/cli-cheatsheet.md.


Common Use Cases

Use CaseApproach
Kenya-targeted SMS / USSDAfrica's Talking. Twilio Kenya is $0.3134/segment with no local numbers
US transactional SMSMessaging Service + registered 10DLC Campaign (or verified toll-free) + statusCallback
OTP / phone verificationVerify v2. No 10DLC registration needed, $0.05 per success + channel
Screen numbers on signupLookup v2 line_type_intelligence / sms_pumping_risk
Outbound voice reminderclient.calls.create with <Say> TwiML
Voice AI agent / phone receptionist<Connect><ConversationRelay> + WebSocket server + Claude ($0.07/min + voice)
Inbound SMS / IVRWebhook route returning TwiML, signature-validated
WhatsApp (US/global)whatsapp: addresses. Templates by contentSid outside 24h
Nonprofit SMS (donation portal)A2P Charity / 501(c)(3) campaign type ($3/mo)
Agent docs lookupHosted MCP https://mcp.twilio.com/docs (twilio__search → twilio__retrieve)

Troubleshooting

IssueFix
30034 on US SMSNumber isn't in an approved A2P 10DLC Campaign's Messaging Service. Finish Brand + Campaign and add the number to the sender pool
30032 from a toll-free numberToll-free verification is not approved. Submit or fix it in Console > Phone Numbers > Regulatory Information
30007 carrier filteringContent or opt-in issue. Check that the registered campaign samples match real traffic. Avoid public URL shorteners
validateRequest always falseSign the exact public URL. Rebuild from x-forwarded-host + https behind a proxy, and parse the body first
ConversationRelay connects then dropsHandshake signature rejected, url not wss://, or AI/ML addendum not accepted in Console
ConversationRelay voice clippedDon't trim LLM tokens. Send last: true only on the final token
Verify wrong code but no errorExpected: status: "pending". Only "approved" means verified
max_attempts_reached / 404 on checkThe verification is spent or expired (10 min). Start a new one
21610 recipient opted outThey replied STOP. Twilio blocks until START. Respect it
21408 / 21606 geo or permissionEnable the destination in Messaging Geo Permissions, or use a sender that supports the country
63016 WhatsAppOutside the 24h window, or template sent as body. Use contentSid + contentVariables
60601 Lookup on +1 CanadaNeeds NPAC approval for Canadian line-type data
Poor delivery / high cost in KenyaWrong provider. Switch to Africa's Talking
twilio CLI won't starttwilio-cli 7.x needs Node.js >= 22

codeAmani notes

  • Secrets stay server-side. TWILIO_AUTH_TOKEN and TWILIO_API_KEY_SECRET live only in server env / the Hazina vault. Never NEXT_PUBLIC_, never in client bundles, never logged. Use API keys for REST and the Auth Token only for signature validation.
  • Verify before process. Every webhook and ConversationRelay handshake is signature-checked first, then treated as untrusted input (sanitize Body, use DOMPurify for any rendering).
  • US-first default. Twilio is the house choice for US/global SMS, voice, OTP, and voice AI (Florida healthcare clients, Vertiq notifications, donation-portal receipts). Budget A2P registration time (about a week) into every US launch plan.
  • Kenya-targeted projects: SMS/USSD through Africa's Talking, payments through M-Pesa (Daraja), WhatsApp through the Meta Cloud API guide. Twilio is only for occasional international OTP.
  • Payments are not Twilio's job. Stripe is the default rail. SMS receipts are notifications only.
  • AI routing. ConversationRelay brings the voice, Claude is the brain (complex reasoning). Keep the LLM call server-side behind the WebSocket. For healthcare clients, log callSid rather than transcripts that contain PHI. Before handling PHI, sign Twilio's BAA, which requires the Security or Enterprise Edition. Use only products on Twilio's HIPAA Eligible Products list (twilio.com/en-us/hipaa), and confirm ConversationRelay is on that list before any PHI goes through it.
  • Healthcare SMS. Never put PHI in SMS bodies. Send "You have a new message, log in to view". HIPAA workflows on Twilio also require HTTPS webhooks and signature validation.
  • Agents: add the hosted Twilio docs MCP for API lookups. Don't wire @twilio-alpha/mcp with live credentials.