WhatsApp Cloud API webhook handler with typed events in TypeScript
createWebhookHandler wraps the whole receiving side: it answers the verify-token handshake, checks X-Hub-Signature-256 against the raw body, parses the delivery, skips duplicates and calls the handlers you register. The lower-level WebhookHandler, verifySignature and parseWebhook stay available and behave as before.
Create a handler
Section titled “Create a handler”const webhook = createWebhookHandler({ appSecrets: process.env.WHATSAPP_APP_SECRET!, // or an array while you rotate the secret verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!,});appSecrets takes one secret or an array, so you can accept the old and the new App Secret while you rotate. The signature check always runs when a secret is set.
Register event handlers
Section titled “Register event handlers”webhook.on('message', async ({ message, ctx }) => { if (message.type === 'text') { console.log(`text from ${message.from_user_id ?? message.from}: ${message.text.body}`); } console.log(`received on WABA ${ctx.wabaId}`);});webhook.on('status', ({ status }) => { console.log(`message ${status.id} -> ${status.status}`);});webhook.on('call', ({ event }) => { if (event.kind === 'terminate') console.log(`call ended after ${event.value.duration ?? 0}s`);});webhook.on('template', ({ event }) => { console.log(`template event: ${event.kind}`);});webhook.on('unknown', ({ field, value }) => { console.log(`field ${field} is not modelled yet`, value);});// on() returns a function that removes the handler again.const stop = webhook.on('error', ({ error }) => console.error(error));stop();| Event | Payload | Meta webhook fields |
|---|---|---|
message |
message, ctx |
messages (one event per message) |
status |
status, ctx |
messages (one event per status) |
error |
error, ctx |
messages (one event per errors[] entry) |
call |
event (connect, terminate, status) |
calls |
flow |
event (kind is the flow event name) |
flows |
template |
event |
message_template_status_update, message_template_quality_update, template_category_update |
account |
event |
phone_number_quality_update, account_update, account_alerts, user_preferences, business_username_updates |
group |
event |
group_lifecycle_update, group_participants_update, group_settings_update, group_status_update |
unknown |
field, value, ctx |
every other field, with the untouched value |
ctx carries wabaId, field, time, the phone number metadata and the matching contact when the delivery has one. Handlers for one event run one after another. Events of one delivery run at the same time, up to concurrency. A handler that throws is reported to onError and does not stop the others.
Answer Meta
Section titled “Answer Meta”// Node frameworks: pass the raw bytes and answer with the status it returns.const verification = webhook.handleVerification(query); // { statusCode, body }const result = await webhook.handleDelivery(rawBody, signatureHeader);// result.httpStatus is 200, 401, 413 or 500.// Fetch-style runtimes: one call answers both the GET handshake and the POST delivery.const response: Response = await webhook.handleRequest(request);| Situation | Status |
|---|---|
| Missing or wrong signature, or no tenant resolved | 401 |
Body over maxBodyBytes (3 MiB by default) |
413 |
| Valid signature, body that is not JSON or not a webhook | 200, reported to onError |
| Valid delivery | 200 |
A handler threw and retryOnHandlerError is true |
500 |
Method other than GET or POST on handleRequest |
405 |
A valid signature with an unreadable body gets 200 so Meta does not retry a payload that can never parse. The size limit is checked from content-length and again while the body streams in.
By default the handlers run before the answer (ackMode: 'after'). With ackMode: 'before' the handler answers once the delivery is verified and parsed, and runs the handlers in the background. Pass waitUntil so serverless platforms keep the invocation alive; see Edge runtimes.
Options
Section titled “Options”const configured = createWebhookHandler({ appSecrets: [process.env.WHATSAPP_APP_SECRET!, process.env.WHATSAPP_APP_SECRET_OLD!], verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, dedupe: createMemoryDedupe({ ttlMs: 60 * 60 * 1000, maxEntries: 10_000 }), maxEventAgeSeconds: 15 * 60, // skip message and status events older than 15 minutes concurrency: 8, // events handled at the same time within one delivery retryOnHandlerError: true, // answer 500 when a handler throws so Meta redelivers onError: (error, info) => console.error('handler failed', info.event?.name, error),});Meta can deliver the same event more than once. The default dedupe keys are message:<id> and status:<id>:<status>; other events are not deduplicated. createMemoryDedupe keeps keys in memory for one process, so serverless instances do not share it. Pass your own WebhookDedupe backed by Redis or a database for that. With retryOnHandlerError, keys of failed events are released so Meta’s retry is not skipped.
Set allowUnsigned: true only when no secret is configured on purpose. Without any secret, the handler accepts unsigned deliveries and emits a one-time warning (WHATSAPP_WEBHOOK_UNSIGNED) unless you set it.
Serve several apps
Section titled “Serve several apps”const multiTenant = createWebhookHandler({ // Pick the secrets and verify token from the request, for example from the URL path. resolveTenant: (incoming) => { const tenantId = new URL(incoming.url).pathname.split('/').pop(); return tenantId === 'acme' ? { appSecrets: process.env.ACME_APP_SECRET!, verifyToken: process.env.ACME_VERIFY_TOKEN! } : undefined; // unknown tenant: 401 on POST, 403 on GET },});Related: verify the signature, handling events and testing your webhook handler.
Independent open-source project. Not affiliated with, endorsed by or sponsored by Meta or WhatsApp. Released under the MIT licence. Source on GitHub.