Quick answer: Twilio posts each WhatsApp message to your Express route as a form-encoded request (From, Body, MediaUrl0) signed in X-Twilio-Signature, and waits 15 seconds by default for TwiML. Meta’s Cloud API first checks your URL with a GET hub.challenge, then posts JSON signed in X-Hub-Signature-256 and retries anything but a 200 for up to 7 days.
If you asked “show me a sample Node.js webhook for the Twilio WhatsApp API, with a Meta WhatsApp Cloud API comparison”, this page is the code. Below are two minimal Express 5 handlers, one per route, written for Node.js 20 or later. The Twilio one uses the official twilio helper library (version 6.3.1, published 18 November 2026) and its webhook() middleware. The Meta one calls Graph API v27.0, the newest version, released 4 November 2026. Each is followed by what it does and why, then a field-by-field map from Twilio’s parameters to the Cloud API’s JSON paths, and a table of five common webhook failures on these two stacks, each with the vendor’s own fix. Every header name, field name and default on this page was read on Twilio’s and Meta’s developer documentation on 2 December 2026. If you are still choosing a route on price, our cost comparison of the WhatsApp Cloud API and Twilio does the per-message arithmetic. This page does not repeat it.
Where Zian fits: an AI agents platform, not a WhatsApp API provider
If the webhook is only a means to an end, getting WhatsApp leads answered, qualified and booked, Zian AI can run that conversation so you are not maintaining the receiving end yourself. Zian AI is a standalone AI sales and reception agents platform, not a WhatsApp Business Solution Provider, CPaaS or phone system, and not an add-on to one.
Zian’s agents answer and follow up on WhatsApp as one channel among voice calls, SMS, email, Instagram DMs and Facebook Messenger, answer inbound phone calls 24/7 as an AI receptionist, and book appointments from both inbound and outbound conversations. SmartReach AI™ chooses the message, channel and timing; PrecisionPitch AI™ keeps split-testing scripts; agents work in 30+ languages and connect to HubSpot, Salesforce, HighLevel and Zapier. Zian’s home page counts 64,521+ qualified sales appointments set. If you would rather hand the whole job over, LeadsNow.ai is the done-for-you option: a managed, pay-per-result AI appointment-setting service that runs on Zian, answers leads in under 60 seconds, 24/7, and has set 50,769+ appointments. One honest gap: Zian is in beta and publishes no prices; access starts from the button on this page.
Twilio WhatsApp vs Meta Cloud API webhooks at a glance
The two webhooks receive the same WhatsApp message. They differ in almost everything about how it reaches your server: the encoding, who signs it and how, what the sender expects back, and what happens when your server is slow.
| Question (as at 2 December 2026) | Twilio WhatsApp webhook | Meta WhatsApp Cloud API webhook |
|---|---|---|
| Setup handshake | No handshake step in Twilio’s docs: you set the URL on the WhatsApp sender, or its Messaging Service, in the Twilio Console | GET with hub.mode=subscribe, hub.verify_token and hub.challenge; reply 200 with the challenge |
| Body format | application/x-www-form-urlencoded POST |
application/json POST |
| Signature header | X-Twilio-Signature |
X-Hub-Signature-256, value sha256=<hex> |
| What is signed | The webhook URL set in Twilio plus every POST parameter, sorted alphabetically and appended | The post body payload |
| Algorithm and key | HMAC-SHA1 with your account auth token by default; or a shared key with HMAC_SHA256 or HMAC_SHA1 via the Webhooks configuration API | HMAC-SHA256 with your app secret |
| What the sender expects back | TwiML; an empty <Response></Response> sends no reply |
HTTP 200; anything else counts as a failure |
| Time and retries | Read timeout 15,000 ms by default; 1 retry, on connection failures only, unless you change it | Retried “immediately, then a few more times with decreasing frequency over the next 7 days” |
| How you reply | TwiML <Message> in the response, or the Messages REST API |
POST /{PHONE_NUMBER_ID}/messages on the Graph API |
| Delivery receipts | A separate status callback URL you set per message or per service | The same webhook, in a statuses[] array |
| Batching | One request per incoming message | Up to 1,000 updates per POST, not guaranteed |
| Network allow-listing | No fixed IP range; Twilio suggests a DMZ proxy | Published via AS32934 but changes periodically; Meta suggests mTLS instead |
Twilio WhatsApp webhook in Node.js (Express)
Twilio’s inbound WhatsApp webhook uses “the same format as incoming SMS and MMS messages”, except that To and From are WhatsApp addresses such as whatsapp:+61412345678. The request is synchronous: Twilio “expects to receive TwiML in response”. This handler answers with an empty TwiML document straight away and sends the real reply through the REST API, so a slow model or CRM lookup cannot run into Twilio’s timeout.
// twilio-whatsapp-webhook.js: Twilio WhatsApp webhook (Node.js 20+, Express 5, twilio 6.x)
// Env: TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN (read by twilio.webhook), TWILIO_API_KEY,
// TWILIO_API_SECRET, TWILIO_WHATSAPP_FROM (e.g. whatsapp:+61400000000),
// TWILIO_INBOUND_URL and TWILIO_STATUS_URL (the exact public URLs set in Twilio), PORT
const express = require('express');
const twilio = require('twilio');
const app = express();
const client = twilio(process.env.TWILIO_API_KEY, process.env.TWILIO_API_SECRET, {
accountSid: process.env.TWILIO_ACCOUNT_SID,
});
const form = express.urlencoded({ extended: false }); // Twilio posts form-encoded, not JSON
// 1. Inbound WhatsApp message, signed with X-Twilio-Signature
app.post(
'/webhooks/twilio',
form,
twilio.webhook({ url: process.env.TWILIO_INBOUND_URL }), // 400 if unsigned, 403 if invalid
(req, res) => {
const { From, Body = '', NumMedia = '0', MessageSid } = req.body;
// From is "whatsapp:+61..." or, when no phone number is shared, the BSUID (whatsapp:US.1A2B...);
// ExternalUserId carries the BSUID; MediaUrl0..MediaUrl{n-1} hold attachments
res.type('text/xml').send('<Response></Response>'); // answer now, reply by REST below
const text = Body || (Number(NumMedia) > 0 ? '(media message)' : '');
client.messages
.create({
from: process.env.TWILIO_WHATSAPP_FROM,
to: From,
body: `Thanks, we received: ${text.slice(0, 200)}`,
statusCallback: process.env.TWILIO_STATUS_URL,
})
.catch((err) => console.error('twilio send', MessageSid, err));
}
);
// 2. Status callbacks for messages you sent: queued, sent, delivered, read, failed, undelivered
app.post(
'/webhooks/twilio/status',
form,
twilio.webhook({ url: process.env.TWILIO_STATUS_URL }),
(req, res) => {
const { MessageSid, MessageStatus, ErrorCode } = req.body;
console.log('status', MessageSid, MessageStatus, ErrorCode ?? '');
res.sendStatus(204);
}
);
// Media: Twilio media URLs need HTTP Basic auth (API key SID and secret)
async function downloadTwilioMedia(mediaUrl) {
const key = `${process.env.TWILIO_API_KEY}:${process.env.TWILIO_API_SECRET}`;
const auth = `Basic ${Buffer.from(key).toString('base64')}`;
const file = await fetch(mediaUrl, { headers: { Authorization: auth } });
if (!file.ok) throw new Error(`media download ${file.status}`);
return { mimeType: file.headers.get('content-type'), data: Buffer.from(await file.arrayBuffer()) };
}
module.exports = { app, downloadTwilioMedia };
if (require.main === module) app.listen(process.env.PORT || 3000);
What each part does. express.urlencoded() runs first because Twilio does not send JSON, and the signature is computed over the decoded form parameters. twilio.webhook() then reads TWILIO_AUTH_TOKEN from the environment, rebuilds the signature and compares it. In twilio-node’s source, a request with no X-Twilio-Signature header gets a 400, a bad signature gets a 403, and a missing token gets a 500. The url option is the most useful line in the file. It pins the URL the library signs to the exact public address you typed into Twilio, instead of letting it rebuild one from what Express sees behind a proxy. Twilio is explicit that the URL must match byte for byte: “If you decode or re-encode the URL, signature validation fails.”
Replying. For a fixed reply you can skip the REST call and return TwiML instead: const twiml = new twilio.twiml.MessagingResponse(); twiml.message('Thanks'); res.type('text/xml').send(twiml.toString());. That reply has to come back inside the read timeout, which defaults to 15,000 milliseconds. Twilio’s help centre documents the empty <Response></Response> as the way to receive SMS and MMS without sending an auto-response, and the WhatsApp webhook shares that format. The status route answers with 204, one of the two responses Twilio’s TwiML page recommends for status callbacks; the other is a 200 with an empty <Response/>.
Signing keys. The sample uses the default auth-token signature because it is what every account has on day one. Twilio’s security page now says “Shared keys are the preferred way to sign webhooks in production”. They are created through the Webhooks configuration API, can use HMAC_SHA256, and rotate without touching your auth token. One catch when you move a URL into a Webhooks configuration API Setting: Twilio warns that “A Setting that omits retryPolicy doesn’t retry at all”, while a plain URL with no override “retries once on connect timeout”, so set retryPolicy explicitly. Requests signed that way carry an X-Twilio-Webhooks-Signature-Settings header naming the key and algorithm, and the twilio-node 6.3.1 middleware accepts a sharedKeySecret option for them. Twilio’s own advice is to validate with its SDK rather than your own code: “Don’t implement your own signature validation.” Parameters can be added “without advance notice”, so always pass the whole req.body, never a list of fields you expect.
Meta WhatsApp Cloud API webhook in Node.js (Express)
The direct route has two halves: a GET that proves you own the URL, and the POSTs that carry messages and statuses. Before either works, Meta needs an HTTPS endpoint with “a valid TLS or SSL digital security certificate” (self-signed certificates are not supported), a subscription to the messages field, and a token with whatsapp_business_messaging. Our guide to applying for WhatsApp Business API access walks through the account, number and system-user token steps that come first.
// meta-whatsapp-webhook.js: WhatsApp Cloud API webhook (Node.js 20+, Express 5)
// Env: META_VERIFY_TOKEN, META_APP_SECRET, META_ACCESS_TOKEN (system-user token), PORT
const crypto = require('node:crypto');
const express = require('express');
const GRAPH = 'https://graph.facebook.com/v27.0';
const app = express();
// 1. Verification: Meta sends GET ?hub.mode=subscribe&hub.verify_token=...&hub.challenge=...
app.get('/webhooks/meta', (req, res) => {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode === 'subscribe' && token === process.env.META_VERIFY_TOKEN) {
return res.status(200).type('text/plain').send(challenge);
}
return res.sendStatus(403);
});
// 2. Events: a JSON POST signed with X-Hub-Signature-256 (HMAC-SHA256, app secret)
app.post(
'/webhooks/meta',
express.json({
limit: '3mb', // Meta: payloads can be up to 3 MB; the parser default is 100kb
verify: (req, res, buf) => { req.rawBody = buf; }, // keep the exact bytes Meta signed
}),
(req, res) => {
const sig = req.get('X-Hub-Signature-256');
if (!validMetaSignature(req.rawBody, sig, process.env.META_APP_SECRET)) {
return res.sendStatus(401);
}
res.sendStatus(200); // acknowledge first, then do the slow work
handleMetaPayload(req.body).catch((err) => console.error('meta webhook', err));
}
);
function validMetaSignature(rawBody, header, appSecret) {
if (!rawBody || !appSecret || typeof header !== 'string') return false;
if (!header.startsWith('sha256=')) return false;
const hex = crypto.createHmac('sha256', appSecret).update(rawBody).digest('hex');
const expected = Buffer.from(hex);
const received = Buffer.from(header.slice('sha256='.length));
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}
const seen = new Set(); // Meta retries for up to 7 days: keep this in Redis or your database
async function handleMetaPayload(body) {
if (!body || body.object !== 'whatsapp_business_account') return;
for (const entry of body.entry ?? []) {
for (const change of entry.changes ?? []) {
if (change.field !== 'messages') continue;
const value = change.value;
for (const st of value.statuses ?? []) {
// sent / delivered / read / failed, matched to your send by st.id (the wamid)
console.log('status', st.id, st.status, st.errors?.[0]?.code ?? '');
}
for (const msg of value.messages ?? []) {
if (seen.has(msg.id)) continue;
seen.add(msg.id);
const text = msg.type === 'text' ? msg.text.body : `(${msg.type} message)`;
// A user with a username can arrive without `from`: reply to the BSUID instead
const address = msg.from ? { to: msg.from } : { recipient: msg.from_user_id };
const phoneNumberId = value.metadata.phone_number_id;
await sendText(phoneNumberId, address, `Thanks, we received: ${text.slice(0, 200)}`);
}
}
}
}
async function sendText(phoneNumberId, address, body) {
const res = await fetch(`${GRAPH}/${phoneNumberId}/messages`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.META_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messaging_product: 'whatsapp',
recipient_type: 'individual',
...address,
type: 'text',
text: { body },
}),
});
if (!res.ok) throw new Error(`Graph API ${res.status}: ${await res.text()}`);
return res.json(); // "accepted", not delivered: delivery arrives later in statuses[]
}
// Media: the webhook carries an ID; swap it for a URL, then download with the same token
async function downloadMetaMedia(mediaId) {
const auth = { Authorization: `Bearer ${process.env.META_ACCESS_TOKEN}` };
const info = await (await fetch(`${GRAPH}/${mediaId}`, { headers: auth })).json();
const file = await fetch(info.url, { headers: auth }); // this URL expires after 5 minutes
if (!file.ok) throw new Error(`media download ${file.status}`);
return { mimeType: info.mime_type, data: Buffer.from(await file.arrayBuffer()) };
}
module.exports = { app, validMetaSignature, handleMetaPayload, downloadMetaMedia };
if (require.main === module) app.listen(process.env.PORT || 3000);
Verification. Meta sends the GET whenever you save or edit the Callback URL or Verify token in the App Dashboard. Meta’s own wording: “If the request is valid, respond with HTTP status 200 and the hub.challenge value.” Anything else and Meta “will consider your webhook endpoint unverified, and webhooks will not be sent”. The handler returns the challenge as plain text and a 403 otherwise.
The signature is over bytes, not objects. Meta defines the header value as an “HMAC-SHA256 hash, calculated using the post body payload and your app secret as the secret key”. The verify hook on express.json() receives “a Buffer of the raw request body” before parsing, so the handler keeps those exact bytes and hashes them. Comparing with crypto.timingSafeEqual after a length check avoids leaking the match through timing. Skipping the check is the costly shortcut: a public URL that accepts unsigned JSON will act on anyone’s POST.
Acknowledge, then act. The handler sends 200 before it does any slow work, then walks every entry[].changes[], because Meta aggregates updates into batches of up to 1,000 and says “batching cannot be guaranteed”. Inbound messages sit in value.messages[]; receipts for messages you sent sit in value.statuses[], and one outgoing message can produce “up to three separate webhooks” (sent, delivered and read), plus failed, and played for voice messages. A failed status omits the contacts array, so match it to your send by statuses[].id. The seen set skips a message ID already handled, because Meta’s retries “can result in duplicate webhook notifications”. Keep it in Redis or your database rather than in process memory.
Who to reply to. Since the business-scoped user ID (BSUID) rollout, Meta warns that when a user has adopted a username, from and wa_id may be omitted, and “an integration that relies only on phone number fields will not be able to process messages from these users”. The handler replies to from when it is present and otherwise sends to from_user_id through the recipient property. Send the request with neither and Meta returns error code 100. Authentication templates cannot go to a BSUID. A successful send response “only indicates that the API successfully accepted your request”; delivery arrives later in statuses[]. Free-form text only works inside the 24-hour customer service window. Outside it you need an approved template, and our guide to why WhatsApp templates are rejected covers getting one through review.
Need the agent, not the webhook? Zian’s AI sales and reception agents answer and follow up on WhatsApp, SMS, email, voice calls, Instagram DMs and Facebook Messenger, and book the appointment. Book a Demo
Field-by-field mapping: Twilio parameters to Cloud API JSON paths
If you are moving a Twilio handler to the Cloud API, or running both, this is the translation table. Twilio parameters are flat form fields on req.body. Meta paths start from value = entry[].changes[].value, and “message” means one item of value.messages[].
| What you need | Twilio parameter | Cloud API JSON path | Watch for |
|---|---|---|---|
| Sender’s number | From (whatsapp:+61412345678) |
messages[0].from (61412345678, no plus sign) |
Meta can omit from for username users; Twilio then puts the BSUID in From |
| Stable user ID (BSUID) | ExternalUserId (whatsapp:US.1A2B…) |
messages[0].from_user_id or contacts[0].user_id |
Up to 128 alphanumeric characters; valid only inside the business portfolio that generated it |
| WhatsApp ID | WaId |
contacts[0].wa_id |
Meta: “a WhatsApp user’s ID and phone number may not always match” |
| Profile name | ProfileName |
contacts[0].profile.name |
Display text only; never a key |
| Your receiving number | To |
metadata.display_phone_number, plus metadata.phone_number_id |
You send with phone_number_id, not the display number |
| Message ID for dedupe | MessageSid (34 characters) |
messages[0].id (a wamid. string) |
Twilio also sends I-Twilio-Idempotency-Token to mark retries |
| Text | Body (up to 1,600 characters) |
messages[0].text.body when type is text |
Check messages[0].type before reading text |
| Media | NumMedia, MediaUrl0, MediaContentType0 |
messages[0].image.id (or audio, video, document…) and mime_type; then GET /v27.0/{media-id} returns a url |
Twilio media URLs need HTTP Basic auth; Meta’s URL expires after 5 minutes and the media ID after 7 days |
| Forwarded flags | Forwarded, FrequentlyForwarded |
messages[0].context.forwarded, context.frequently_forwarded |
Meta includes context only for forwarded messages: forwarded means five times or fewer, frequently_forwarded more than five |
| Click-to-WhatsApp ad | ReferralSourceId, ReferralCtwaClid |
messages[0].referral.source_id, referral.ctwa_clid |
Only on messages that started from an ad |
| Delivery status | Separate POST to your StatusCallback: MessageStatus (queued, sent, delivered, undelivered, read, failed) and ErrorCode |
Same webhook: statuses[0].status (sent, delivered, read, failed, played) and statuses[0].errors |
Twilio gives “no guarantee” that callbacks arrive in order; key on the message ID and time |
| Delivery failure detail | ErrorCode, plus ChannelStatusMessage for WhatsApp |
statuses[0].errors[]; account-level errors in value.errors; unsupported inbound in messages[0].errors |
Meta surfaces errors in three places; log all three |
Two rows trip up most migrations. First, media: Twilio hands you a URL you fetch with Basic auth, using an API key SID and secret per its media docs, while Meta hands you an ID you exchange for a short-lived URL and then download with your bearer token. Meta has been gradually adding a direct url field to media webhooks since 12 November 2025, but says it “may not be available to you immediately”, so keep the ID route. Second, status: on Twilio you choose where receipts go per message; on Meta they share the inbound URL, so the same handler must tell messages[] from statuses[].
5 webhook failures and the fix
Each row pairs a failure with the vendor sentence that explains it. Rows 1, 2, 3 and 5, and the duplicate half of row 4, were reproduced against fixtures (see the next section); the Twilio timeout in row 4 was not.
| Failure | Route | Cause | Fix | Vendor basis |
|---|---|---|---|---|
| 1. Every Meta signature check fails | Cloud API | The HMAC is computed over JSON.stringify(req.body), which changes whitespace and escaping, so the bytes differ from what Meta signed |
Capture the raw Buffer in express.json({ verify }) and hash that |
Meta: the hash is “calculated using the post body payload and your app secret” |
| 2. Twilio returns 403 behind ngrok or a load balancer | Twilio | TLS ends upstream, so Express sees http://localhost:3000/… while Twilio signed https://your-domain/… |
Pass the public URL as twilio.webhook({ url }); locally, Twilio says use ngrok http 3000 |
Twilio: “the request URL that your Express application sees does not match the URL Twilio used” |
| 3. Large Meta payloads get a 413 | Cloud API | The Express JSON parser’s default limit is 100kb |
Set limit: '3mb' on the Meta route only, to match Meta’s stated maximum; body-parser’s README advises against limits far above its default, so do not go higher |
Meta: “Webhook payloads can be up to 3 MB” |
| 4. Duplicate replies, or replies that never arrive | Both | Meta retries non-200 responses for up to 7 days; Twilio waits 15,000 ms for TwiML and by default retries only connection failures | Return 200 (Meta) or empty TwiML (Twilio) first, reply through the API, dedupe on messages[].id or MessageSid |
Meta: retries “can result in duplicate webhook notifications”; Twilio connection-override defaults (rt 15000, rc 1, rp ct) |
| 5. Some users never get a reply | Both | The code keys users on phone number; username users arrive without from (Meta) or with a BSUID in From (Twilio) |
Key users on from_user_id or ExternalUserId; on Meta, send with recipient when to is absent |
Meta: phone-only integrations “will not be able to process messages from these users” |
Two quieter failures sit next to these. Meta’s troubleshooting list says “some webhooks will not be sent if your app is in Dev mode”, so check the app is Live before debugging code. And on Twilio, connection overrides in the URL fragment (#rt=…&rc=…) are, in Twilio’s words, “the legacy approach”; the fragment is left out of the signature, and Twilio now points to the Webhooks configuration API for timeouts and retries. Twilio also lets you set a Fallback URL on the WhatsApp sender, which it calls “if a fatal error occurs” on the primary URL and sends ErrorCode and ErrorUrl with the request.
How we tested the two handlers
We did not install the twilio or express packages for this page. Both handlers passed node --check on Node.js 24.14.1. We then ran them against fixtures using small local stand-ins for Express routing and the Twilio middleware. The Twilio stand-in re-creates the algorithm twilio-node implements, HMAC-SHA1 over the URL plus sorted parameters, and was checked against a test vector from twilio-node’s own test suite before use. The Meta fixture is Meta’s own documented text-message payload, signed separately with openssl dgst -sha256 -hmac. All 19 checks passed.
| Check | Input | Result |
|---|---|---|
| Meta GET verification | Correct and wrong hub.verify_token |
200 with the challenge; 403 |
| Meta signature | OpenSSL-signed body; tampered body; missing header; wrong secret | Accepted; 401; 401; rejected |
| Failure 1 | Same payload re-serialised with JSON.stringify |
Signature no longer matches |
| Dedupe | Same signed payload delivered twice | One Graph API send, not two |
| Failure 5 (Meta) | Username user with no from |
Reply sent with recipient set to the BSUID |
| Statuses | A delivered status payload |
200, nothing sent |
| Failure 3 | 150 KB payload | 200 with limit: '3mb'; 413 at the 100kb default |
| Twilio inbound | Signed form POST; unsigned; tampered Body |
Empty TwiML plus REST send to From; 400; 403 |
| Failure 2 | Signature rebuilt from http://localhost:3000 |
Does not match the public-URL signature |
| Media helpers | Meta media ID; Twilio media URL | ID swapped for URL, bearer token sent; Basic auth header built |
What this does not prove: behaviour of the real packages beyond what their documentation and source say, and live delivery from Twilio or Meta. Run your own test from the Twilio Console and the App Dashboard’s test-webhook button before production. Meta notes there is no API for “fetching historical webhook data”, so log payloads you may need later.
Which WhatsApp webhook should you build?
The code above is the smaller half of the decision. Both routes put the same Meta rules on the conversation itself: the 24-hour window, templates and opt-in. What differs is who owns the plumbing.
| If this is you | Run it on | Why |
|---|---|---|
| You want WhatsApp leads answered, followed up and booked, and the webhook is not the product | Zian (platform) or LeadsNow.ai (done for you) | The agent runs the conversation across WhatsApp and five other channels; you do not host the receiving end |
| You already use Twilio for SMS or voice, and want one signature scheme and one API | Twilio webhook | Same form-encoded webhook and Messages API as SMS; Fallback URL and status callbacks built in |
| You want Meta’s fields first-hand (BSUIDs, referral data, pricing objects in statuses) and no intermediary | Cloud API webhook | Raw JSON from Meta, one endpoint for messages and statuses, versioned Graph API |
| You need a working bot this week without writing a server | A no-code tool | Our n8n WhatsApp AI agent build handles verification and signatures in its trigger node |
On cost, the two routes differ by Twilio’s per-message fee in both directions, which our Cloud API vs Twilio cost page (linked above) works through line by line.
WhatsApp webhook questions
Does Twilio’s WhatsApp webhook send JSON?
No. Twilio sends inbound WhatsApp messages as an application/x-www-form-urlencoded POST, the same format as SMS and MMS, so use express.urlencoded() before twilio.webhook(). Twilio can also send JSON payloads, signed with an added bodySHA256 query parameter, but its incoming-message webhook is documented as form-encoded.
What does Meta’s X-Hub-Signature-256 sign?
The request body, using HMAC-SHA256 with your app secret as the key; the header value is “sha256=” followed by the hex digest. Meta’s webhook endpoint guide describes it as a hash “calculated using the post body payload and your app secret”. Hash the raw bytes you received, not a re-serialised object.
Why does my Twilio signature validation fail on ngrok?
Because the URL your app reconstructs does not match the URL Twilio signed. Twilio signs the exact webhook URL you configured plus the sorted POST parameters. Behind ngrok or a TLS-terminating proxy your app sees http and a local host. Pass the public URL to twilio.webhook({ url }), or run ngrok http 3000 as Twilio suggests.
How fast must a WhatsApp webhook respond?
Twilio waits 15,000 milliseconds by default for a response and, by default, retries only connection failures. The Meta webhook pages we read, as at 2 December 2026, give no response-time figure; they say any status other than 200, or a failed delivery, is retried for up to 7 days. Answer first, then do slow work.
Which Graph API version should the Cloud API code use?
v27.0 is the latest Graph API version, introduced on 4 November 2026; Meta’s own send and media examples use it. v26.0 (29 July 2026) has no published end date yet, and v25.0 is available until 29 July 2028. Pin a version in one constant and upgrade on purpose.
Can one Node.js server handle both Twilio and Meta?
Yes. Give each its own route and its own body parser: urlencoded for Twilio, JSON with a raw-body capture for Meta. Never apply a global JSON parser in front of the Meta route without the verify hook, or the original bytes are gone before you can check the signature.
Where every figure on this page comes from
| Figure | Who published it | Link | Date read |
|---|---|---|---|
| 15,000 ms default read timeout; 1 retry; retry policy ct; connection overrides “the legacy approach” | Twilio | Webhook connection overrides | 2 December 2026 |
| A Setting without retryPolicy does not retry; a plain URL retries once on connect timeout | Twilio | Migrate to the Webhooks configuration API | 2 December 2026 |
| HMAC-SHA1 with auth token by default; shared keys with HMAC_SHA256; parameters sorted and appended to the URL | Twilio | Secure webhooks | 2 December 2026 |
| webhook() middleware returns 403 when unauthorised; ngrok URL mismatch | Twilio | Secure your Express app | 2 December 2026 |
| 400 / 403 / 500 responses; url and sharedKeySecret options | Twilio (twilio-node source) | src/webhooks/webhooks.ts | 2 December 2026 |
| twilio 6.3.1 published 18 November 2026; Node.js 20 or later | npm registry (Twilio package) | npm: twilio | 2 December 2026 |
| Body up to 1,600 characters; 34-character MessageSid; WhatsApp parameters | Twilio | Twilio’s request to your incoming message webhook URL | 2 December 2026 |
| whatsapp: address format; Fallback URL with ErrorCode and ErrorUrl | Twilio | WhatsApp Business Platform with Twilio | 2 December 2026 |
| ExternalUserId; BSUID up to 128 alphanumeric characters | Twilio | WhatsApp key concepts | 2 December 2026 |
| Status callbacks: 204 or 200 with empty Response | Twilio | TwiML for Programmable Messaging | 2 December 2026 |
| Status callbacks not guaranteed in order | Twilio | Track outbound message status | 2 December 2026 |
| Media URLs need HTTP Basic auth | Twilio | Media resource | 2 December 2026 |
| Empty Response sends no auto-reply (SMS/MMS article) | Twilio help centre | Receive messages without sending a response | 2 December 2026 |
| hub.challenge handshake; batches of up to 1,000; retries over 7 days | Meta | Create a webhook endpoint | 2 December 2026 |
| Payloads up to 3 MB; duplicate notifications; Live mode | Meta | WhatsApp webhooks overview | 2 December 2026 |
| Up to three status webhooks per message; BSUID fields (the “ID and phone number may not always match” note is on the text and image message references) | Meta | messages webhook reference | 2 December 2026 |
| Media URL valid 5 minutes; webhook media ID 7 days | Meta | Media | 2 December 2026 |
| Media url field rolling out from 12 November 2025 | Meta | Image messages webhook reference | 2 December 2026 |
| Error code 100 with neither to nor recipient | Meta | Service messages | 2 December 2026 |
| Graph API v27.0 introduced 4 November 2026; v25.0 available until 29 July 2028 | Meta | Graph API changelog | 2 December 2026 |
| JSON parser default limit 100kb; verify receives the raw Buffer | Express (body-parser) | body-parser README | 2 December 2026 |
Rather have WhatsApp answered than build it? Zian’s AI agents answer inbound calls 24/7, follow up on WhatsApp and four other messaging channels, and book appointments in 30+ languages. Book a Demo