WhatsApp Cloud API Webhook in Node.js: Signatures & Retries
Fix WhatsApp Cloud API webhook bugs in Node.js and Express: hub.verify_token 403s, X-Hub-Signature-256 raw-body HMAC checks, and wamid deduplication.

TL;DR
Capture the raw request buffer before JSON parsing for X-Hub-Signature-256, return HTTP 200 immediately before slow work, and deduplicate every event by message.id (wamid) in SQL or Redis.
If you have integrated the WhatsApp Cloud API in Node.js and Express, you have probably seen this exact sequence: your webhook works cleanly in local ngrok testing, goes live, and within an hour fails signature checks on emoji messages, throws 403 during dashboard verification, or sends users the exact same automated reply three times in a row.
None of those bugs are caused by Meta's API being flaky. They happen because Express middleware alters raw request bodies before HMAC verification, Meta expects an HTTP 200 OK in a few seconds before triggering retry storms, and WhatsApp delivers both incoming messages and delivery-status events to the exact same endpoint.
Here is the production Express + PostgreSQL/Redis setup to fix every one of those failure modes.
1. Fixing GET /webhook 403 Verification Failures
When you register a callback URL in the Meta Developer Dashboard, Meta sends a GET request with three query parameters:
hub.mode(alwayssubscribe)hub.verify_token(must match the secret string you pasted into the dashboard)hub.challenge(a random integer string that you must echo back untouched)
Two subtle mistakes trigger 403 Forbidden or verification failures here:
- Returning JSON instead of plain text: Calling
res.json({ challenge })fails Meta's check. You must returnres.status(200).send(String(challenge)). - Not validating exact token equality: Always return
403explicitly if eithermode !== 'subscribe'ortoken !== process.env.WHATSAPP_VERIFY_TOKEN.
import express from 'express';
const app = express();
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 === process.env.WHATSAPP_VERIFY_TOKEN) {
return res.status(200).type('text/plain').send(String(challenge));
}
return res.sendStatus(403);
});
2. Why X-Hub-Signature-256 Fails on Emojis (Raw Buffer Fix)
Meta signs every POST webhook payload using HMAC-SHA256 with your App Secret and attaches it in the X-Hub-Signature-256 header formatted as sha256=<hex>.
The #1 bug developers hit is mounting global app.use(express.json()), hashing JSON.stringify(req.body), and wondering why signature verification randomly fails whenever a customer sends an emoji, Arabic text, or escaped slash /. JSON.stringify(req.body) re-serializes characters and whitespace differently than the exact byte payload Meta hashed.
The fix: Capture the raw Buffer inside the verify hook of express.json(), compute the HMAC against req.rawBody, check buffer byte lengths first, and compare with crypto.timingSafeEqual:
import crypto from 'node:crypto';
import express from 'express';
// Capture raw request bytes BEFORE JSON parsing mutates whitespace or unicode escapes
app.use(
express.json({
verify: (req, _res, buf) => {
req.rawBody = buf;
},
})
);
function hasValidMetaSignature(req) {
const header = req.get('x-hub-signature-256');
const appSecret = process.env.WHATSAPP_APP_SECRET;
if (!header || !appSecret || !Buffer.isBuffer(req.rawBody)) {
return false;
}
const [scheme, signatureHex] = header.split('=');
if (scheme !== 'sha256' || !signatureHex) {
return false;
}
const expectedHex = crypto
.createHmac('sha256', appSecret)
.update(req.rawBody)
.digest('hex');
const receivedBuf = Buffer.from(signatureHex, 'hex');
const expectedBuf = Buffer.from(expectedHex, 'hex');
// timingSafeEqual throws RangeError if buffer lengths differ
if (receivedBuf.length !== expectedBuf.length) {
return false;
}
return crypto.timingSafeEqual(receivedBuf, expectedBuf);
}
Always check receivedBuf.length !== expectedBuf.length before calling crypto.timingSafeEqual. Without that length guard, a malformed or truncated header crashes your request handler with RangeError: Input buffers must have the same byte length.
3. Stopping Meta's Duplicate Retry Storms
Meta enforces a strict response timeout on webhook deliveries. If your handler queries PostgreSQL, calls an LLM API, or sends a reply over the Graph API before answering Meta's POST request, slow requests exceed the deadline.
When a delivery times out or returns a 5xx, Meta treats it as failed and retries with exponential backoff for up to 7 days. That causes duplicate replies, duplicate CRM leads, and wasted AI tokens.
Acknowledge valid webhooks immediately with res.sendStatus(200) right after signature verification, then hand the payload off to a worker queue (BullMQ, Redis, or a database job table) or an isolated async handler:
app.post('/webhook', async (req, res) => {
if (!hasValidMetaSignature(req)) {
return res.sendStatus(401);
}
// Acknowledge immediately so Meta does not mark the delivery as timed out
res.sendStatus(200);
// Enqueue or handle asynchronously after response flush
setImmediate(() => {
processWebhookPayload(req.body).catch((err) => {
console.error('WhatsApp webhook processing error:', err);
});
});
});
(Note: In serverless platforms like Vercel or AWS Lambda where the runtime freezes once res.sendStatus(200) returns, push the validated payload to Redis/SQS/Upstash before returning 200 OK, since queue insertion takes under 20ms.)
4. Deduplicating Messages with wamid and Ignoring Status Floods
Even with fast 200 OK responses, network blips cause Meta to guarantee at-least-once delivery, meaning you will still occasionally receive the exact same webhook twice.
At the same time, Meta sends message status events (sent, delivered, read, failed) to the same messages field. If you only check changes[0].value, status updates trigger unnecessary database queries or error logs.
Handle both cleanly:
- Ignore events that only contain
value.statuses(unless you are explicitly updating delivery receipts). - Deduplicate incoming user messages using
message.id(the uniquewamid.HBg...string), not the sender phone number or message text. - Enforce uniqueness atomically at the database or Redis layer so two parallel retries cannot pass a check-then-insert race condition.
-- PostgreSQL / MySQL idempotency table
CREATE TABLE processed_whatsapp_messages (
message_id VARCHAR(255) PRIMARY KEY,
sender_wa_id VARCHAR(32) NOT NULL,
received_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
async function claimMessageOnce(pool, messageId, senderWaId) {
// Atomic insert: returns 1 row only for the first worker that claims this wamid
const result = await pool.query(
`INSERT INTO processed_whatsapp_messages (message_id, sender_wa_id)
VALUES ($1, $2)
ON CONFLICT (message_id) DO NOTHING
RETURNING message_id`,
[messageId, senderWaId]
);
return result.rowCount === 1;
}
async function processWebhookPayload(body) {
if (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 ?? {};
// Skip outbound delivery receipts when routing inbound customer replies
if (Array.isArray(value.statuses)) {
for (const status of value.statuses) {
// Optionally log failed deliveries: status.errors
if (status.status === 'failed') {
console.warn('Outbound WhatsApp message failed:', status.id, status.errors);
}
}
}
for (const message of value.messages ?? []) {
const claimed = await claimMessageOnce(dbPool, message.id, message.from);
if (!claimed) {
continue; // Duplicate retry safely skipped
}
await routeInboundMessage(message, value.contacts?.[0]);
}
}
}
}
If you prefer Redis over SQL for short-lived deduplication, use atomic SET key 1 EX 86400 NX:
const wasNew = await redis.set(`wa:msg:${message.id}`, '1', { EX: 86400, NX: true });
if (!wasNew) continue;
5. Production Checklist & Common Errors
| Symptom | Root Cause | Exact Fix |
|---|---|---|
| Dashboard returns 403 on setup | Token mismatch or JSON response body | Return String(challenge) as text/plain with status 200 |
| Valid emojis fail HMAC check | Hashing JSON.stringify(req.body) |
Capture raw Buffer via express.json({ verify }) |
RangeError on bad signatures |
Calling timingSafeEqual on mismatched lengths |
Check receivedBuf.length !== expectedBuf.length first |
| Bot answers the same message 3 times | Slow reply triggers Meta retry timeout | Return 200 OK fast and deduplicate on message.id |
Bot crashes on empty messages |
Reading value.messages[0] on status webhooks |
Check value.statuses and iterate value.messages ?? [] |
Frequently Asked Questions
Why does Meta keep retrying my WhatsApp webhook after I already answered the user?
Meta only cares whether your webhook HTTP endpoint returned a 2xx status code before the request deadline, not whether you sent a WhatsApp reply via the Graph API. If calling your AI model or CRM takes 8 seconds before calling res.sendStatus(200), Meta marks the webhook timed out and queues retries for days.
Can I disable X-Hub-Signature-256 verification in production?
Never. Without verifying the HMAC-SHA256 signature against your App Secret, anyone who discovers your webhook URL can forge fake user messages, exhaust your OpenAI/CRM quotas, and poison database records.
How long should I keep processed wamid records?
Meta retries failed deliveries for up to 7 days. Keeping wamid keys for 7 to 14 days (either via Redis TTL or a scheduled SQL cleanup job) prevents all retry duplicates cleanly without growing your table indefinitely.
Does setImmediate work on Vercel or AWS Lambda for WhatsApp webhooks?
No. Serverless functions freeze or terminate execution immediately after sending the HTTP 200 response. On serverless hosts, push the verified event payload into a fast queue (SQS, Upstash QStash, or BullMQ on Redis) and wait for the queue write to settle before calling res.sendStatus(200).
References & Further Reading
- Internal: Khandowa Law Case Study: Automated WhatsApp Consultation Intake
- Internal: How REST APIs Work: HTTP Methods, Status Codes & JSON
- Internal: How Database Indexes Work: B-Trees & SQL Query Tuning
- External: Meta Developers - WhatsApp Cloud API Webhooks Documentation
- External: Node.js Crypto Docs - crypto.timingSafeEqual
Related articles

Written by Sabtain Ali
Full-Stack Developer
I build backends and full-stack web apps with React, Node.js, Laravel, and MySQL - including the CommutersLink carpooling backend in Pakistan and web tools for WHO and WOAH.