Verify Twilio webhooks
Twilio signs every request in X-Twilio-Signature, so you can confirm it came from Twilio and wasn't changed. By default the signature is a base64 HMAC-SHA1, keyed with your primary Auth Token, of the full URL Twilio called followed by each POST parameter's name and value, sorted by name. The body isn't signed as bytes, so a URL rewritten by a proxy breaks it just as a changed parameter does. A JSON body, as Event Streams sends, is covered by a bodySHA256 query parameter inside the signed URL. Twilio's SDKs include a RequestValidator for all of this, and Twilio tells you to use it rather than your own code.
Twilio has two systems that send you webhooks. Messaging, Voice and other products call a URL you set on a number or resource, with form parameters and no event type field. Event Streams sends JSON CloudEvents with a type. The events list names Event Streams types and Conversations (classic) actions, because a status callback has no event name to list. SendGrid's email events are separate: see SendGrid webhooks.
The facts
X-Twilio-Signature Format: a base64 digest with no prefix, e.g. L/OH5YylLD5NRKLltdqwSvS0BnU=
{url}{name1}{value1}{name2}{value2}… The full URL Twilio called, including scheme, query string and any port it keeps, then each POST parameter's name and value, sorted by name with no delimiters. The body itself isn't signed. A GET has its parameters in the URL. A JSON body adds nothing to the string: the URL has a bodySHA256 query parameter, the SHA-256 hex of the raw body, so check that too.
Recompute the signature over the full URL and the sorted POST parameters, and compare Twilio webhook secret
By default Twilio signs with your account's primary Auth Token. A Webhook Setting can sign with a shared key you create instead, per URL pattern. Keep it in an environment variable, not in source code.
- The Auth Token is on the Twilio Console at twilio.com/console. It belongs to the account, not to an endpoint.
- Use the primary Auth Token. A newly created secondary token signs nothing until it is promoted to primary, so keep validating with the old one until then.
- To sign with a key you manage, create a SharedKey in the Webhooks configuration API, name it in a Webhook Setting and apply that with a Webhook Rule. Each account can hold 50.
- A SharedKey's
secretis returned only in the response that creates it and can't be recovered. -
X-Twilio-Webhooks-Signature-Settings: key=<sharedKeyId>,algorithm=<algorithm>says which key signed a request. When that header is absent, the Auth Token did. - Rotate a shared key by creating a new SharedKey and Setting, accepting both secrets in your handler, moving the Rule over, then deleting the old ones.
- Twilio's docs describe no test and live split for signing.
Source: Twilio docs ↗
Code
// Generated with: twilio-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const twilio = require('twilio');
const app = express();
/**
* Verify an X-Twilio-Signature for a form-encoded webhook.
*
* Uses the official Twilio SDK, which implements:
* HMAC-SHA1(authToken, url + concat(sortedParamName + paramValue)) -> base64
*
* @param {string} authToken - Your Twilio Auth Token
* @param {string} signature - The X-Twilio-Signature header value
* @param {string} url - The exact URL Twilio called (scheme + host + path + query)
* @param {object} params - Parsed form parameters
* @returns {boolean}
*/
function verifyTwilioWebhook(authToken, signature, url, params) {
if (!signature) return false;
try {
return twilio.validateRequest(authToken, signature, url, params);
} catch {
return false;
}
}
// Reconstruct the full URL Twilio called. Respect proxy headers when present
// so this works behind tunnels and load balancers.
function buildWebhookUrl(req) {
const proto = req.headers['x-forwarded-proto'] || req.protocol || 'https';
const host = req.headers['x-forwarded-host'] || req.headers.host;
return `${proto}://${host}${req.originalUrl}`;
}
// Twilio sends most webhooks as application/x-www-form-urlencoded.
app.post('/webhooks/twilio',
express.urlencoded({ extended: false }),
(req, res) => {
const signature = req.headers['x-twilio-signature'];
const url = buildWebhookUrl(req);
const params = req.body || {};
if (!verifyTwilioWebhook(process.env.TWILIO_AUTH_TOKEN, signature, url, params)) {
console.error('Twilio signature verification failed');
return res.status(403).send('Invalid signature');
}
// Route by which parameters are present — Twilio doesn't put an event field
// in the body; the "event" is the URL you configured + the params shape.
// Message status callback (queued, sending, sent, delivered, undelivered, failed)
if (params.MessageSid && params.MessageStatus) {
handleMessageStatus(params);
return res.status(204).send();
}
// Call status callback (queued, ringing, in-progress, completed, busy, failed, no-answer, canceled)
if (params.CallSid && params.CallStatus && params.Direction !== 'inbound' && !params.Body) {
handleCallStatus(params);
return res.status(204).send();
}
// Recording status callback
if (params.RecordingSid && params.RecordingStatus) {
handleRecordingStatus(params);
return res.status(204).send();
}
// Incoming SMS / MMS — respond with TwiML
if (params.MessageSid && typeof params.Body !== 'undefined') {
const twiml = handleIncomingSms(params);
res.type('text/xml');
return res.send(twiml);
}
// Incoming voice call — respond with TwiML
if (params.CallSid && params.Direction === 'inbound') {
const twiml = handleIncomingCall(params);
res.type('text/xml');
return res.send(twiml);
}
console.log('Unhandled Twilio webhook params:', Object.keys(params));
res.status(204).send();
}
);
function handleIncomingSms(params) {
console.log(`Incoming SMS ${params.MessageSid} from ${params.From}: ${params.Body}`);
// Your code: persist message, trigger downstream logic, etc.
return '<?xml version="1.0" encoding="UTF-8"?>'
+ '<Response><Message>Thanks, got your message!</Message></Response>';
}
function handleIncomingCall(params) {
console.log(`Incoming call ${params.CallSid} from ${params.From}`);
// Your code: route the call, play a recorded message, gather digits, etc.
return '<?xml version="1.0" encoding="UTF-8"?>'
+ '<Response><Say>Hello from Twilio webhooks.</Say></Response>';
}
function handleMessageStatus(params) {
console.log(`Message ${params.MessageSid} status: ${params.MessageStatus}`);
switch (params.MessageStatus) {
case 'queued':
case 'sending':
case 'sent':
// In-flight states — usually informational
break;
case 'delivered':
// Your code: mark message as delivered in your DB
break;
case 'undelivered':
case 'failed':
console.error(`Message ${params.MessageSid} failed: ErrorCode=${params.ErrorCode}`);
// Your code: retry / alert / surface to user
break;
default:
// Channel-specific statuses (e.g. WhatsApp "read") land here
break;
}
}
function handleCallStatus(params) {
console.log(`Call ${params.CallSid} status: ${params.CallStatus}`);
// Statuses: queued, ringing, in-progress, completed, busy, failed, no-answer, canceled
// Your code: update your call record
}
function handleRecordingStatus(params) {
console.log(`Recording ${params.RecordingSid} status: ${params.RecordingStatus}`);
// Your code: download or process the recording at params.RecordingUrl
}
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = { app, verifyTwilioWebhook, buildWebhookUrl };
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/twilio`);
});
} // Generated with: twilio-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
/**
* Verify an X-Twilio-Signature for a form-encoded webhook.
*
* Algorithm (matches the official Twilio SDKs):
* signedString = url + concat(sortedParamName + paramValue)
* signature = base64( HMAC-SHA1( authToken, signedString ) )
*/
export function verifyTwilioSignature(
authToken: string,
signature: string,
url: string,
params: Record<string, string>,
): boolean {
if (!signature) return false;
const data = Object.keys(params)
.sort()
.reduce((acc, key) => acc + key + params[key], url);
const expected = crypto
.createHmac('sha1', authToken)
.update(Buffer.from(data, 'utf-8'))
.digest('base64');
try {
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
} catch {
// Different lengths -> invalid
return false;
}
}
/**
* Reconstruct the URL Twilio signed. Prefer WEBHOOK_BASE_URL so this matches
* the URL you configured in the Twilio Console exactly.
*/
function buildWebhookUrl(request: NextRequest): string {
const parsed = new URL(request.url);
const pathAndQuery = parsed.pathname + parsed.search;
const base = process.env.WEBHOOK_BASE_URL;
if (base) {
return base.replace(/\/$/, '') + pathAndQuery;
}
const proto = request.headers.get('x-forwarded-proto') || parsed.protocol.replace(':', '');
const host = request.headers.get('x-forwarded-host') || request.headers.get('host') || parsed.host;
return `${proto}://${host}${pathAndQuery}`;
}
export async function POST(request: NextRequest) {
const signature = request.headers.get('x-twilio-signature') || '';
const url = buildWebhookUrl(request);
// Twilio sends application/x-www-form-urlencoded; read as text and parse.
const rawBody = await request.text();
const params: Record<string, string> = {};
for (const [key, value] of new URLSearchParams(rawBody)) {
params[key] = value;
}
const authToken = process.env.TWILIO_AUTH_TOKEN || '';
if (!verifyTwilioSignature(authToken, signature, url, params)) {
console.error('Twilio signature verification failed');
return new NextResponse('Invalid signature', { status: 403 });
}
// Incoming SMS / MMS -> respond with TwiML
if (params.MessageSid && typeof params.Body !== 'undefined' && !params.MessageStatus) {
console.log(`Incoming SMS ${params.MessageSid} from ${params.From}: ${params.Body}`);
const twiml =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<Response><Message>Thanks, got your message!</Message></Response>';
return new NextResponse(twiml, {
status: 200,
headers: { 'Content-Type': 'text/xml' },
});
}
// Message status callback: queued | sending | sent | delivered | undelivered | failed
if (params.MessageSid && params.MessageStatus) {
console.log(`Message ${params.MessageSid} status: ${params.MessageStatus}`);
if (params.MessageStatus === 'failed' || params.MessageStatus === 'undelivered') {
console.error(`Delivery problem ErrorCode=${params.ErrorCode}`);
// Your code: surface to user / retry
}
return new NextResponse(null, { status: 204 });
}
// Incoming voice call -> respond with TwiML
if (params.CallSid && params.Direction === 'inbound' && !params.Body) {
console.log(`Incoming call ${params.CallSid} from ${params.From}`);
const twiml =
'<?xml version="1.0" encoding="UTF-8"?>' +
'<Response><Say>Hello from Twilio webhooks.</Say></Response>';
return new NextResponse(twiml, {
status: 200,
headers: { 'Content-Type': 'text/xml' },
});
}
// Call status callback: queued | ringing | in-progress | completed | busy | failed | no-answer | canceled
if (params.CallSid && params.CallStatus) {
console.log(`Call ${params.CallSid} status: ${params.CallStatus}`);
return new NextResponse(null, { status: 204 });
}
// Recording status callback
if (params.RecordingSid && params.RecordingStatus) {
console.log(`Recording ${params.RecordingSid} status: ${params.RecordingStatus}`);
return new NextResponse(null, { status: 204 });
}
console.log('Unhandled Twilio webhook params:', Object.keys(params));
return new NextResponse(null, { status: 204 });
} # Generated with: twilio-webhooks skill
# https://github.com/hookdeck/webhook-skills
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Request, Response, HTTPException
from twilio.request_validator import RequestValidator
load_dotenv()
app = FastAPI()
def _validator() -> RequestValidator:
"""Build the RequestValidator on each call so tests can monkeypatch TWILIO_AUTH_TOKEN."""
return RequestValidator(os.environ.get("TWILIO_AUTH_TOKEN", ""))
def build_webhook_url(request: Request) -> str:
"""
Reconstruct the URL Twilio signed.
Twilio computes the signature over the exact URL you registered. Behind a
proxy, the request URL FastAPI sees may differ — prefer an explicit base.
"""
base = os.environ.get("WEBHOOK_BASE_URL")
if base:
path = request.url.path
query = request.url.query
path_and_query = f"{path}?{query}" if query else path
return base.rstrip("/") + path_and_query
forwarded_proto = request.headers.get("x-forwarded-proto")
forwarded_host = request.headers.get("x-forwarded-host")
if forwarded_proto and forwarded_host:
path = request.url.path
query = request.url.query
path_and_query = f"{path}?{query}" if query else path
return f"{forwarded_proto}://{forwarded_host}{path_and_query}"
return str(request.url)
def verify_twilio_webhook(
auth_token: str,
signature: str,
url: str,
params: dict,
) -> bool:
"""Verify an X-Twilio-Signature for a form-encoded webhook using the Twilio SDK."""
if not signature:
return False
try:
return RequestValidator(auth_token).validate(url, params, signature)
except Exception:
return False
@app.post("/webhooks/twilio")
async def twilio_webhook(request: Request):
form = await request.form()
params = {key: form[key] for key in form}
signature = request.headers.get("X-Twilio-Signature", "")
url = build_webhook_url(request)
if not _validator().validate(url, params, signature):
raise HTTPException(status_code=403, detail="Invalid signature")
# Twilio doesn't put an event field in the body — route by parameter shape
# and (for voice) by Direction.
# Incoming SMS / MMS -> respond with TwiML
if params.get("MessageSid") and "Body" in params and "MessageStatus" not in params:
return _handle_incoming_sms(params)
# Message status callback: queued, sending, sent, delivered, undelivered, failed
if params.get("MessageSid") and params.get("MessageStatus"):
_handle_message_status(params)
return Response(status_code=204)
# Incoming voice call -> respond with TwiML
if params.get("CallSid") and params.get("Direction") == "inbound" and "Body" not in params:
return _handle_incoming_call(params)
# Call status callback: queued, ringing, in-progress, completed, busy, failed, no-answer, canceled
if params.get("CallSid") and params.get("CallStatus"):
_handle_call_status(params)
return Response(status_code=204)
# Recording status callback
if params.get("RecordingSid") and params.get("RecordingStatus"):
_handle_recording_status(params)
return Response(status_code=204)
print(f"Unhandled Twilio webhook params: {list(params.keys())}")
return Response(status_code=204)
def _handle_incoming_sms(params: dict) -> Response:
print(f"Incoming SMS {params['MessageSid']} from {params.get('From')}: {params.get('Body')}")
twiml = (
'<?xml version="1.0" encoding="UTF-8"?>'
"<Response><Message>Thanks, got your message!</Message></Response>"
)
return Response(content=twiml, media_type="text/xml")
def _handle_incoming_call(params: dict) -> Response:
print(f"Incoming call {params['CallSid']} from {params.get('From')}")
twiml = (
'<?xml version="1.0" encoding="UTF-8"?>'
"<Response><Say>Hello from Twilio webhooks.</Say></Response>"
)
return Response(content=twiml, media_type="text/xml")
def _handle_message_status(params: dict) -> None:
status = params["MessageStatus"]
print(f"Message {params['MessageSid']} status: {status}")
if status in ("failed", "undelivered"):
print(f" delivery problem ErrorCode={params.get('ErrorCode')}")
def _handle_call_status(params: dict) -> None:
print(f"Call {params['CallSid']} status: {params['CallStatus']}")
# Statuses: queued, ringing, in-progress, completed, busy, failed, no-answer, canceled
def _handle_recording_status(params: dict) -> None:
print(f"Recording {params['RecordingSid']} status: {params['RecordingStatus']}")
# Statuses: in-progress, completed, absent
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 3000))) Or install the Twilio webhooks skill:
npx skills add hookdeck/webhook-skills --skill twilio-webhooks
Common failures
The URL isn't the one Twilio called
A proxy that terminates TLS, a rewritten trailing slash or a decoded query string all change the signed string. Twilio keeps the port for SMS callbacks and drops it for voice callbacks over HTTPS. Leave out any # connection override fragment, because that isn't signed.
Middleware changed the parameters
Trimming whitespace breaks the match, and Laravel's TrimStrings does it by default. So does a parser that drops empty values, as Python's parse_qs does by default. Sort names case-sensitively if you build the string yourself.
The wrong key
A secondary Auth Token doesn't sign anything until it's promoted to primary. If X-Twilio-Webhooks-Signature-Settings is present, a shared key signed the request, and that header names the key and algorithm.
A JSON body validated as form parameters
For application/json, don't pass the body's properties as parameters. Use the SDK's method for JSON bodies, such as validateRequestWithBody, with the raw body string, and pass the full URL with bodySHA256 in it.
Queue Twilio deliveries before they reach your handler.
Event Gateway accepts each Twilio delivery, queues it and retries failures on your schedule, with a log of every attempt.