Handling events
extractMessages and extractStatuses flatten a payload. Message types the SDK does not model still parse; handle them in the default branch.
import { extractMessages, extractStatuses, parseWebhook } from '@solvejet/whatsapp-cloud-api';
const payload = parseWebhook(rawBody); // after verifying the signaturefor (const message of extractMessages(payload)) { switch (message.type) { case 'text': console.log(`text from ${message.from_user_id ?? message.from}: ${message.text.body}`); break; case 'interactive': console.log(message.interactive.button_reply?.id ?? message.interactive.list_reply?.id); break; default: console.log(`unhandled message type: ${message.type}`); }}for (const status of extractStatuses(payload)) { console.log(`message ${status.id} -> ${status.status}`);}Return 200 fast and do the work afterwards. Meta retries deliveries, so deduplicate on the message id (wamid).
extractMessages, extractStatuses and parse read the messages webhook field only. Other fields, such as calls, message_template_status_update or account_update, are not parsed into messages or statuses. Their payload is still available in parsed.raw. To get typed events for those fields (call, flow, template, account, group, plus unknown for the rest), use parseWebhookEvents(rawBody) or createWebhookHandler.
Webhook handler
Section titled “Webhook handler”createWebhookHandler answers the handshake, verifies X-Hub-Signature-256 over the raw body, parses the delivery, skips duplicates and calls your handlers.
import { createMemoryDedupe, createWebhookHandler } from '@solvejet/whatsapp-cloud-api';
const webhook = createWebhookHandler({ appSecrets: process.env.WHATSAPP_APP_SECRET!, // a string or an array (secret rotation) verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!, dedupe: createMemoryDedupe(),});
webhook.on('message', async ({ message, ctx }) => { console.log(ctx.wabaId, message.id, message.type);});webhook.on('status', ({ status }) => console.log(status.id, status.status));Pass the raw body to handleDelivery(rawBody, signatureHeader) (Express, Fastify) or the whole Request to handleRequest(request) (Next.js, Hono, Workers, Bun, Deno). handleVerification(query) answers the GET handshake. Both delivery methods return the status to send.
Events: message, status, error, call, flow, template, account, group and unknown. Every event has a ctx with wabaId, field, time, metadata and the matching contact. Fields the SDK does not model arrive as unknown with the untouched value. parseWebhookEvents(body) gives the same events without a handler.
| 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 a webhook | 200, reported to onError |
| Valid delivery | 200 |
A handler threw, retryOnHandlerError: true |
500 |
Other method on handleRequest |
405 with Allow: GET, POST |
Options:
ackMode:'after'(default) runs the handlers before answering.'before'answers once the delivery is verified and parsed and runs the handlers in the background. PasswaitUntil(option or second argument ofhandleRequest) so serverless platforms keep the invocation alive.dedupe: skips events Meta delivered twice. Default keys aremessage:<id>andstatus:<id>:<status>; override withdedupeKey.createMemoryDedupeis per process, so use your ownWebhookDedupewhen several instances share traffic.maxEventAgeSeconds: skips old message and status events.concurrency(default 8): events handled at the same time within one delivery.retryOnHandlerError: answer500when a handler throws so Meta redelivers.resolveTenant(request): pick secrets and verify token per request for several apps.onError(error, info): receives handler errors and invalid envelopes. Defaults toconsole.error.allowUnsigned: with no secret configured, accepting unsigned deliveries logs a one-time warning (WHATSAPP_WEBHOOK_UNSIGNED). Settrueto silence it. When secrets are set, the signature is always required.
The IncomingMessage union now includes order, unsupported, edit and revoke messages. If you check a switch on message.type for exhaustiveness with a never assignment, add the new cases or a default branch. isKnownMessage(message) narrows a message to the modelled types.
Edge runtimes
Section titled “Edge runtimes”@solvejet/whatsapp-cloud-api/web exports the handler, parsers, dedupe and verifySignatureAsync without any node: import. It verifies signatures with Web Crypto.
import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api/web';
export default { async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { const webhook = createWebhookHandler({ appSecrets: env.WHATSAPP_APP_SECRET, verifyToken: env.WHATSAPP_VERIFY_TOKEN, ackMode: 'before', }); webhook.on('message', ({ message }) => console.log(message.id)); return webhook.handleRequest(request, { waitUntil: (promise) => ctx.waitUntil(promise) }); },};For waitUntil, use ctx.waitUntil on Cloudflare, waitUntil from @vercel/functions or after() from next/server on Vercel. Long-running servers on Node, Bun and Deno do not need it. Runtime support lists what CI runs.
Testing your webhook handler
Section titled “Testing your webhook handler”@solvejet/whatsapp-cloud-api/testing builds deliveries and signed requests, so you can test handlers in-process.
import { createWebhookHandler } from '@solvejet/whatsapp-cloud-api/web';import { buildWebhookPayload, createTestRequest } from '@solvejet/whatsapp-cloud-api/testing';
const webhook = createWebhookHandler({ appSecrets: 'test-secret' });webhook.on('message', ({ message }) => console.log(message.id));
const request = await createTestRequest({ payload: buildWebhookPayload('text'), secret: 'test-secret',});const response = await webhook.handleRequest(request); // 200buildWebhookPayload kinds: text, status, call, template_status, flow, account_update, group. signWebhookBody(body, secret) returns the sha256=<hex> header value. Both are async-signing helpers that run on Node 20+, Bun, Deno and workerd.
Independent open-source project. Not affiliated with, endorsed by or sponsored by Meta or WhatsApp. Released under the MIT licence. Source on GitHub.