Short answer: a WhatsApp webhook in Node.js is an HTTPS endpoint, usually built with Express, that answers Meta's GET verification handshake by echoing hub.challenge, then receives POST events with incoming messages and status updates. You validate each POST with the X-Hub-Signature-256 HMAC, return 200 quickly, and reply through the Graph API with fetch.
This tutorial builds that endpoint step by step with code you can run. It covers the official WhatsApp Cloud API first, then shows the same pattern for Zapini's own webhooks, which work for numbers connected by QR Code or by the Cloud API. If you need a conceptual overview of APIs and webhooks before writing code, read our guide on how the WhatsApp API and webhooks send and receive messages.
What is a WhatsApp API webhook?
A webhook is a URL that WhatsApp (or a platform in front of it) calls every time something happens, so your server never has to poll for new messages. Instead of asking "is there anything new?" every few seconds, you register an endpoint and the provider pushes events to it.
With the WhatsApp Cloud API, Meta sends three broad kinds of events to your webhook:
- Incoming messages: text, images, audio, documents, locations, button replies and more, inside
value.messages. - Status updates for messages you sent:
sent,delivered,readorfailed, insidevalue.statuses. - Account-level changes, such as template status updates, depending on which webhook fields you subscribed to in your Meta app.
Your job on the Node.js side is always the same: verify the endpoint, authenticate each request, parse the payload, acknowledge it fast and process it asynchronously.
What do you need before you start?
You need Node.js 18 or newer, a public HTTPS URL and, for the Cloud API, a Meta developer app with WhatsApp added. Meta does not deliver webhooks to plain HTTP or to localhost.
- Node.js 18+: it includes a global
fetch, so you do not need axios or node-fetch. - A public HTTPS URL: in development, a tunnel such as ngrok or Cloudflare Tunnel works; in production, put the app behind a reverse proxy with a valid certificate.
- Meta credentials: the App Secret (App settings, Basic), a Phone Number ID and an access token with WhatsApp messaging permission. A system user token is the usual choice for production because temporary tokens expire.
- A verify token: any random string you invent. You type it in the Meta dashboard and keep the same value in your environment variables.
Create the project:
mkdir whatsapp-webhook && cd whatsapp-webhook
npm init -y
npm install express
# Node.js 18+ ships a global fetch, no extra HTTP library needed
Add "type": "module" to package.json so the import syntax below works, and export VERIFY_TOKEN, APP_SECRET, WA_TOKEN and PHONE_NUMBER_ID as environment variables. Never hard-code them in the source.
How does the verify token handshake work?
When you save the callback URL in the Meta dashboard, Meta sends a GET request with hub.mode=subscribe, your hub.verify_token and a random hub.challenge. If the token matches, you return the challenge as plain text with status 200; otherwise you return 403.
// server.js
import express from 'express';
import crypto from 'node:crypto';
const app = express();
const { VERIFY_TOKEN, APP_SECRET, WA_TOKEN, PHONE_NUMBER_ID } = process.env;
// Keep the raw bytes: the signature is computed over them, not over parsed JSON
app.use(express.json({
verify: (req, _res, buf) => { req.rawBody = buf; }
}));
// 1) Verification handshake (Meta calls this once when you save the URL)
app.get('/webhook', (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 === VERIFY_TOKEN) {
return res.status(200).send(challenge);
}
return res.sendStatus(403);
});
Notice the verify callback in express.json(). It stores the raw request body in req.rawBody before Express parses it. You need those exact bytes in the next step: if you re-serialize the parsed object with JSON.stringify, spacing and character escaping can differ from what Meta signed, and the signature check will fail even for legitimate requests.
How do you validate X-Hub-Signature-256 in Node.js?
Every POST from Meta carries an X-Hub-Signature-256 header with the value sha256= followed by an HMAC-SHA256 of the raw body, keyed with your App Secret. Recompute it and compare in constant time; reject the request if it does not match.
function isValidMetaSignature(req) {
const header = req.get('X-Hub-Signature-256') || '';
const [algo, received] = header.split('=');
if (algo !== 'sha256' || !received || !req.rawBody) return false;
const expected = crypto
.createHmac('sha256', APP_SECRET)
.update(req.rawBody)
.digest('hex');
const a = Buffer.from(received, 'hex');
const b = Buffer.from(expected, 'hex');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
Three details matter here. First, use the App Secret, not the access token and not the verify token. Second, use crypto.timingSafeEqual instead of === so an attacker cannot learn the signature byte by byte from response times. Third, check that both buffers have the same length first, because timingSafeEqual throws when they differ. Without this check anyone who discovers your URL could inject fake "incoming messages" into your system.
How do you parse the webhook payload?
Cloud API payloads are nested: entry[] contains changes[], and each change.value may hold a messages array, a statuses array, or both. Loop defensively, because any of these arrays may be missing.
const seen = new Set(); // use Redis or your DB in production
app.post('/webhook', (req, res) => {
if (!isValidMetaSignature(req)) return res.sendStatus(401);
// Acknowledge fast; do the work after responding
res.sendStatus(200);
for (const entry of req.body.entry ?? []) {
for (const change of entry.changes ?? []) {
const value = change.value ?? {};
for (const msg of value.messages ?? []) {
if (seen.has(msg.id)) continue; // retries can deliver the same id twice
seen.add(msg.id);
const text = msg.type === 'text' ? msg.text.body : `[${msg.type}]`;
console.log(`From ${msg.from}: ${text}`);
handleIncoming(msg).catch(console.error);
}
for (const status of value.statuses ?? []) {
console.log(`Message ${status.id} is now ${status.status}`);
}
}
}
});
The important pattern is acknowledge first, process later. Meta expects a 200 quickly; if your endpoint is slow or returns an error, Meta treats the delivery as failed and retries it. That means the same message can reach you more than once, which is why the example skips message ids it has already seen. In production, store processed ids in Redis or in your database with a unique index instead of an in-memory Set, and move heavy work (calling an AI model, writing to a CRM) to a queue.
Useful fields on each message: from (the sender's number in international format, without +), id (the WhatsApp message id), timestamp, type and a type-specific object such as text.body, image.id or interactive.button_reply. Contact names arrive in value.contacts[].profile.name.
How do you reply to a message with the Graph API and fetch?
To reply, send a POST to https://graph.facebook.com/{version}/{PHONE_NUMBER_ID}/messages with a Bearer token and a JSON body containing messaging_product: "whatsapp", the recipient and the message object.
async function sendText(to, body) {
const url = `https://graph.facebook.com/v21.0/${PHONE_NUMBER_ID}/messages`;
const res = await fetch(url, {
method: 'POST',
headers: {
'Authorization': `Bearer ${WA_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
messaging_product: 'whatsapp',
to,
type: 'text',
text: { body }
})
});
if (!res.ok) throw new Error(`Graph API ${res.status}: ${await res.text()}`);
return res.json();
}
async function handleIncoming(msg) {
if (msg.type === 'text' && /hello|hi/i.test(msg.text.body)) {
await sendText(msg.from, 'Hi! Thanks for your message. How can we help?');
}
}
app.listen(3000, () => console.log('Listening on :3000'));
Pin the Graph API version you tested against (the example uses v21.0; check Meta's changelog for the current one) and update it deliberately. Also remember the policy rule: a free-form text reply is only allowed inside the 24-hour customer service window that opens when the user messages you. Outside that window you must send an approved message template. If you are still deciding which connection model suits you, compare them in WhatsApp Cloud API vs QR Code: which to choose.
How do you receive Zapini webhooks in Node.js?
Zapini sends its own webhook events as a JSON POST with an event name, the instance_uuid, a timestamp and a data object, signed in the X-Webhook-Signature header. The same Express pattern applies: keep the raw body, check the HMAC, respond 2xx, then act.
The advantage is that you get one normalized payload whether the number is connected through the Zapini Gateway (QR Code) or the official Cloud API, so you do not have to write separate parsers for each. Events you can subscribe to include message.received, message.sent, message.status, instance.connected, instance.disconnected, instance.qr and call events such as call.received. Webhooks can be configured on an API token in the panel or per instance through the API, and each one has its own secret.
A message.received delivery looks like this (token_name appears when the webhook belongs to an API token):
{
"event": "message.received",
"instance_uuid": "550e8400-e29b-41d4-a716-446655440000",
"token_name": "My integration",
"timestamp": "2026-11-27T10:30:00-03:00",
"data": {
"message_id": "660e8400-e29b-41d4-a716-446655440001",
"whatsapp_message_id": "3EB0C767D82B4F...",
"sender_number": "5511999999999",
"sender_name": "Maria",
"content": "Hello, is my order on the way?",
"media_type": null,
"media_url": null,
"media_url_proxy": null,
"media_download_url": null,
"timestamp": "2026-11-27T10:30:00-03:00",
"conversation_id": 1234
}
}
Each request also carries the headers X-Webhook-Event and X-Instance-UUID. Here is a complete receiver that validates the signature and answers through the Zapini REST API, which queues the message and applies the instance's sending limits:
// zapini-webhook.js
import express from 'express';
import crypto from 'node:crypto';
const app = express();
const { ZAPINI_WEBHOOK_SECRET, ZAPINI_API_TOKEN } = process.env;
app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }));
function isValidZapiniSignature(req) {
// X-Webhook-Signature = hex HMAC-SHA256 of the JSON body (no "sha256=" prefix)
const received = req.get('X-Webhook-Signature') || '';
const expected = crypto
.createHmac('sha256', ZAPINI_WEBHOOK_SECRET)
.update(req.rawBody)
.digest('hex');
const a = Buffer.from(received, 'hex');
const b = Buffer.from(expected, 'hex');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
app.post('/zapini-webhook', async (req, res) => {
if (!isValidZapiniSignature(req)) return res.sendStatus(401);
res.sendStatus(200); // Zapini expects a 2xx within 10 seconds
const { event, instance_uuid, data } = req.body;
if (event !== 'message.received') return;
console.log(`${data.sender_name} (${data.sender_number}): ${data.content}`);
if (/order/i.test(data.content ?? '')) {
await fetch('https://zapini.app/api/v1/messages/send', {
method: 'POST',
headers: {
'Authorization': `Bearer ${ZAPINI_API_TOKEN}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
instance_id: instance_uuid,
recipient: `+${data.sender_number}`,
message: 'Let me check your order status right now.',
reply_to: data.message_id
})
});
}
});
app.listen(3001);
Zapini's signature is a plain hex HMAC-SHA256 of the JSON body using your webhook secret, without the sha256= prefix Meta uses. Reply with a 2xx within 10 seconds: consecutive failures are counted, and a webhook that keeps failing for hours is disabled automatically until you re-enable it. If you want to push these events into a sales pipeline, see WhatsApp CRM integration for pipeline and forecasting.
Meta Cloud API webhook vs Zapini webhook: what changes?
The handling logic is identical; the differences are in the verification step, the signature header and the payload shape. This table summarizes them.
| Aspect | Meta Cloud API | Zapini |
|---|---|---|
| Endpoint verification | GET handshake with hub.challenge | Not required; you set the URL in the panel or API |
| Signature header | X-Hub-Signature-256: sha256=<hex> | X-Webhook-Signature: <hex> |
| Signing key | App Secret | Webhook secret of the token or instance |
| Payload shape | entry[].changes[].value.messages[] | Flat: event, instance_uuid, data |
| Message text | text.body | data.content |
| Connection types | Cloud API only | QR Code (Zapini Gateway) and Cloud API |
| Sending a reply | Graph API /{PHONE_NUMBER_ID}/messages | POST /api/v1/messages/send |
How do you put a WhatsApp webhook into production safely?
Treat the webhook as a public, security-sensitive endpoint: authenticate every request, make processing idempotent and keep the response path fast. These steps cover the usual failure points.
- Serve over HTTPS with a valid certificate behind Nginx or a load balancer.
- Validate the signature on every POST and reject anything that fails with 401.
- Respond 200 immediately and push the event to a queue (BullMQ, SQS, RabbitMQ) for slow work.
- Deduplicate by message id, since retries can resend the same event.
- Store secrets in environment variables or a secrets manager and rotate them if they leak.
- Log payloads carefully: messages contain personal data, so mask phone numbers and avoid logging media URLs indefinitely.
- Monitor failures: alert when 4xx/5xx responses rise, before the provider starts failing deliveries.
Frequently asked questions
Why does Meta say my callback URL could not be verified?
Usually the GET handler is not returning hub.challenge exactly as plain text with status 200, the verify token does not match the one typed in the dashboard, or the URL is not reachable over public HTTPS. Test it yourself with a browser request containing the three hub.* query parameters.
Why does my X-Hub-Signature-256 check always fail?
The most common cause is computing the HMAC over JSON.stringify(req.body) instead of the raw bytes. Capture the raw body with the verify option of express.json() and make sure you use the App Secret, not the access token.
Why do I receive the same WhatsApp message twice?
Providers retry deliveries that were not acknowledged in time or returned an error. Respond with 200 quickly and deduplicate by the message id (msg.id on Meta, data.message_id or data.whatsapp_message_id on Zapini).
Can I test a WhatsApp webhook on localhost?
Not directly, because the provider must reach a public HTTPS URL. Run a tunnel such as ngrok or Cloudflare Tunnel that forwards a public address to your local port, and register that address as the callback URL.
Can I reply to any user at any time from the webhook?
No. On the official API, free-form messages are only allowed within 24 hours of the user's last message; after that you need an approved template. Sending unsolicited messages also risks blocks and quality rating drops.
Do I need Express to build a WhatsApp webhook in Node.js?
No. Fastify, Koa, NestJS or the native http module work as well. What matters is access to the raw body for signature validation, a fast 200 response and asynchronous processing.
Skip the plumbing and start receiving WhatsApp events
Zapini gives you WhatsApp by QR Code or the official Cloud API, signed webhooks, a REST API, AI agents, flows and a Kanban CRM in one place, so your Node.js code only has to handle business logic. Create your Zapini account and connect your first number.