Twilio Integration Guide

Technology: twilio · Category: comms · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/twilio

Insight:

Twilio is the US/global comms channel: SMS/MMS, Voice, managed OTP via Verify ($0.05 per successful verification plus channel fees), and voice AI agents via ConversationRelay ($0.07/min). In the US you must register before sending: unregistered 10DLC traffic is blocked (error 30034) and unverified toll-free traffic is blocked (30032). Base US SMS is $0.0083/segment plus carrier pass-through fees. For Kenya-targeted projects use Africa's Talking: Twilio Kenya SMS is $0.3134/segment over international routes with no local numbers, versus KES 0.4–0.8 on AT. Validate every inbound webhook and ConversationRelay WebSocket with X-Twilio-Signature.

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

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):

Area Now
SDK twilio 6.2.0: signature comparison moved from the deprecated scmp package to crypto.timingSafeEqual; TwiML <Stream> gains audioFormat/sampleRate. No API breaks.
CLI twilio-cli 7.2.0. The 7.x line requires Node.js >= 22 (the SDK still runs on 20).
MCP Twilio 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 compliance Unregistered 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 AI ConversationRelay (<Connect><ConversationRelay>) is the documented path for LLM voice agents at $0.07/min plus normal voice minutes.
WhatsApp Since 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:

sequenceDiagram
  participant U as "User"
  participant APP as "Your app (Next.js API route)"
  participant V as "Twilio Verify API"
  U->>APP: "Enter phone number"
  APP->>V: "verifications.create {to, channel: sms}"
  V->>U: "SMS - Your code is 482915"
  U->>APP: "Submit code 482915"
  APP->>V: "verificationChecks.create {to, code}"
  V-->>APP: "status: approved | pending"
  APP-->>U: "Verified - issue session"

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

Resource URL
Twilio Docs (root) https://www.twilio.com/docs
Programmable Messaging https://www.twilio.com/docs/messaging
A2P 10DLC (US long codes) https://www.twilio.com/docs/messaging/compliance/a2p-10dlc
Toll-free verification https://www.twilio.com/docs/messaging/compliance/toll-free/console-onboarding
Verify API (OTP) https://www.twilio.com/docs/verify/api
Lookup v2 https://www.twilio.com/docs/lookup/v2-api
Programmable Voice https://www.twilio.com/docs/voice
ConversationRelay https://www.twilio.com/docs/voice/conversationrelay
Webhooks security (signature) https://www.twilio.com/docs/usage/webhooks/webhooks-security
WhatsApp via Twilio https://www.twilio.com/docs/whatsapp
Twilio MCP server https://www.twilio.com/docs/ai/mcp
Node helper library https://github.com/twilio/twilio-node
Product changelog https://www.twilio.com/en-us/changelog

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.

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.

npm install twilio@6.2.0   # Node.js >= 20 (engines field)
// 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.

Sender What you must do Blocked if skipped Throughput / notes
10DLC long code (+1 local) A2P 10DLC Brand + Campaign in Trust Hub, number in the Campaign's Messaging Service sender pool Yes, error 30034 Campaign 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 code Carrier short-code application (weeks) n/a Highest throughput. $1,000–$1,500/quarter lease.
Verify (OTP only) Nothing extra: Verify uses Twilio's pre-registered senders No Use 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):

Fee Sole Proprietor Low-Volume Standard Standard
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)

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.

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.

// 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.

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:

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:

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 Twilio Meaning
setup Sent once on connect: callSid, from, to, customParameters
prompt Caller speech: voicePrompt, lang, last
interrupt Caller talked over TTS: utteranceUntilInterrupt
dtmf Keypress (only with dtmfDetection)
error Session error
To Twilio Meaning
{ 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:

// 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.

// 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 → Kenya Africa'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 numbers None: domestic and international long codes and short codes are not supported Dedicated and shared short codes (KES 15,000/mo or KES 2,000/mo)
Sender ID Alphanumeric pre-registration (certificate of incorporation). Domestic registrations are not supported, and Safaricom requires registration for coverage Local sender ID / short code provisioning
Two-way SMS No (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_):

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):

Variable Example Purpose
TWILIO_ACCOUNT_SID AC… (34 chars) Account identifier
TWILIO_API_KEY_SID SK… API key identifier, paired with the secret
TWILIO_MESSAGING_SERVICE_SID MG… Sender pool + A2P Campaign association
TWILIO_VERIFY_SERVICE_SID VA… One Verify Service per environment
TWILIO_PHONE_NUMBER +15619991234 Voice caller ID / single sender
TWILIO_WHATSAPP_FROM whatsapp:+1… WhatsApp sender
TWILIO_WEBHOOK_BASE_URL https://app.example.com Public 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)

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 Case Approach
Kenya-targeted SMS / USSD Africa's Talking. Twilio Kenya is $0.3134/segment with no local numbers
US transactional SMS Messaging Service + registered 10DLC Campaign (or verified toll-free) + statusCallback
OTP / phone verification Verify v2. No 10DLC registration needed, $0.05 per success + channel
Screen numbers on signup Lookup v2 line_type_intelligence / sms_pumping_risk
Outbound voice reminder client.calls.create with <Say> TwiML
Voice AI agent / phone receptionist <Connect><ConversationRelay> + WebSocket server + Claude ($0.07/min + voice)
Inbound SMS / IVR Webhook 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 lookup Hosted MCP https://mcp.twilio.com/docs (twilio__search → twilio__retrieve)

Troubleshooting

Issue Fix
30034 on US SMS Number 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 number Toll-free verification is not approved. Submit or fix it in Console > Phone Numbers > Regulatory Information
30007 carrier filtering Content or opt-in issue. Check that the registered campaign samples match real traffic. Avoid public URL shorteners
validateRequest always false Sign the exact public URL. Rebuild from x-forwarded-host + https behind a proxy, and parse the body first
ConversationRelay connects then drops Handshake signature rejected, url not wss://, or AI/ML addendum not accepted in Console
ConversationRelay voice clipped Don't trim LLM tokens. Send last: true only on the final token
Verify wrong code but no error Expected: status: "pending". Only "approved" means verified
max_attempts_reached / 404 on check The verification is spent or expired (10 min). Start a new one
21610 recipient opted out They replied STOP. Twilio blocks until START. Respect it
21408 / 21606 geo or permission Enable the destination in Messaging Geo Permissions, or use a sender that supports the country
63016 WhatsApp Outside the 24h window, or template sent as body. Use contentSid + contentVariables
60601 Lookup on +1 Canada Needs NPAC approval for Canadian line-type data
Poor delivery / high cost in Kenya Wrong provider. Switch to Africa's Talking
twilio CLI won't start twilio-cli 7.x needs Node.js >= 22

codeAmani notes

Official docs: