# Receive WhatsApp webhooks in Node.js with Express

> Answer the WhatsApp webhook GET, check X-Hub-Signature-256 on the raw body, parse messages and statuses, and return 200 first, in Express and node:crypto.

Published 2026-11-03. Z-API Omni team.

Receive WhatsApp Cloud API webhooks in Express with two routes on the same path. The GET route echoes `hub.challenge` when `hub.verify_token` matches your token. The POST route reads the body with `express.raw()`, checks `X-Hub-Signature-256` against those bytes, answers 200 and then walks `entry[].changes[].value.messages[]` and `statuses[]`. The server below uses only Express and Node's `crypto` module.

## Install and configure

Express 5 requires Node.js 18 or higher, according to the [Express 5 API page](https://expressjs.com/en/5x/api/express/). You need two secrets. The app secret comes from your Meta app. The verify token is any string you choose and type into the webhook settings of the App Dashboard.

```bash
npm install express@5
export APP_SECRET="APP_SECRET"
export VERIFY_TOKEN="VERIFY_TOKEN"
```

Meta delivers only to an endpoint with a valid certificate. "Your webhook endpoint server must have a valid TLS or SSL digital security certificate", and "Self-signed certificates are not supported" ([Meta create a webhook endpoint, accessed 2026-11-03](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). Put the server behind a reverse proxy or tunnel that holds a real certificate.

## Full Express server

```javascript
// server.js
const express = require('express');
const crypto = require('node:crypto');

const APP_SECRET = process.env.APP_SECRET;
const VERIFY_TOKEN = process.env.VERIFY_TOKEN;
const PORT = process.env.PORT || 3000;

const app = express();
const seen = new Set(); // in-memory dedupe for the demo; use a database table in production

app.get('/webhook', (req, res) => {
  const { 'hub.mode': mode, 'hub.challenge': challenge, 'hub.verify_token': token } = req.query;
  if (mode === 'subscribe' && token === VERIFY_TOKEN) {
    return res.status(200).type('text/plain').send(challenge);
  }
  return res.sendStatus(403);
});

function validSignature(rawBody, header) {
  if (typeof header !== 'string' || !header.startsWith('sha256=')) return false;
  const expected = crypto.createHmac('sha256', APP_SECRET).update(rawBody).digest('hex');
  const received = Buffer.from(header.slice(7), 'utf8');
  const computed = Buffer.from(expected, 'utf8');
  return received.length === computed.length && crypto.timingSafeEqual(received, computed);
}

app.post('/webhook', express.raw({ type: 'application/json', limit: '3mb' }), (req, res) => {
  if (!Buffer.isBuffer(req.body) || !validSignature(req.body, req.get('x-hub-signature-256'))) {
    return res.sendStatus(401);
  }
  let payload;
  try {
    payload = JSON.parse(req.body.toString('utf8'));
  } catch {
    return res.sendStatus(400);
  }
  res.sendStatus(200);
  setImmediate(() => {
    try {
      handle(payload);
    } catch (err) {
      console.error('handler failed', err);
    }
  });
});

function firstTime(key) {
  if (seen.has(key)) return false;
  seen.add(key);
  return true;
}

function handle(payload) {
  if (payload.object !== 'whatsapp_business_account') return;
  for (const entry of payload.entry ?? []) {
    for (const change of entry.changes ?? []) {
      if (change.field !== 'messages') continue;
      const value = change.value ?? {};
      for (const msg of value.messages ?? []) {
        if (!firstTime(`msg:${msg.id}`)) continue;
        const text = msg.type === 'text' ? msg.text?.body : `[${msg.type}]`;
        // Meta leaves `from` out when it cannot include the phone number; use the BSUID
        const sender = msg.from ?? msg.from_user_id;
        console.log(`message ${msg.id} from ${sender} at ${msg.timestamp}: ${text}`);
      }
      for (const st of value.statuses ?? []) {
        if (!firstTime(`status:${st.id}:${st.status}`)) continue;
        console.log(`status ${st.status} for ${st.id} to ${st.recipient_id ?? st.recipient_user_id}`);
        if (st.status === 'failed') console.log(JSON.stringify(st.errors));
      }
    }
  }
}

app.listen(PORT, () => console.log(`listening on ${PORT}`));
```

Run it with `node server.js`, then set the callback URL to `https://YOUR_DOMAIN/webhook` in the App Dashboard and subscribe to the `messages` field.

## The verification GET

When you save the callback URL, Meta sends `GET <CALLBACK_URL>?hub.mode=subscribe&hub.challenge=<HUB.CHALLENGE>&hub.verify_token=<HUB.VERIFY_TOKEN>`. Meta describes `hub.challenge` as "A random string that Meta will generate" and the verify token as "A verification string of your own choosing". "If the request is valid, respond with HTTP status `200` and the `hub.challenge` value."

The route reads the three query keys the same way Meta's own Express echo bot does, and answers 403 on a mismatch ([Meta echo bot, accessed 2026-11-03](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/set-up-whatsapp-echo-bot)). The challenge goes back as the plain-text body.

## Why the POST route uses express.raw

Meta's echo bot registers `app.use(express.json())` and checks no signature, so anyone who finds the URL can post fake messages to it.

Meta defines the signature as an "HMAC-SHA256 hash, calculated using the post body payload and your app secret as the secret key". You compare it with "everything after `sha256=`" in the header, and "If they do not match, consider the payload invalid." Meta doesn't say "raw bytes" in words. Hashing the bytes as received is the reading that works, because a parsed and re-serialized object can differ from what Meta signed. [The signature verification guide](/academy/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) shows how accents and emoji break a re-serialized hash.

`express.raw()` "parses incoming request payloads into a `Buffer`" ([Express 5 API](https://expressjs.com/en/5x/api/express/)). Two of its defaults need changing:

| Option | Express default | Value here | Why |
|---|---|---|---|
| `type` | `"application/octet-stream"` | `'application/json'` | Meta posts `Content-Type: application/json` |
| `limit` | `"100kb"` | `'3mb'` | Meta says "Webhook payloads can be up to 3 MB" |

The 3 MB figure is from [Meta's webhooks overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview) (accessed 2026-11-03). On a content type mismatch `req.body` is `undefined`, so the route tests `Buffer.isBuffer` first, as Express recommends.

The parser sits on the POST route only. A global `express.json()` registered first would read the stream, and every request would then fail the signature check. If other routes need JSON, mount `express.json()` on those routes, or use its `verify(req, res, buf)` hook to keep a copy of `buf`.

`crypto.timingSafeEqual` compares in constant time, but "An error is thrown if `a` and `b` have different byte lengths" ([Node.js crypto](https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b)). The length check before it turns a short forged header into a 401 instead of a thrown error.

## Answer 200 first, then process

The route sends 200 and hands the payload to `setImmediate`. Meta documents no response deadline in seconds. It does say a status code "other than 200" triggers retries, and that "Meta retries delivery with decreasing frequency until the request succeeds, for up to 7 days." With the 200 sent first, an exception in your CRM call or AI step can't turn into a non-200 and a duplicate delivery.

If the process dies inside `handle()`, Meta already has its 200 and won't resend. For anything you can't lose, write the raw payload to a queue or table before the 200. [Webhook queue architecture](/academy/articles/whatsapp-webhook-queue-architecture-workers/) and [saving to your CRM before replying](/academy/articles/save-to-crm-before-replying-whatsapp-automation/) cover both patterns.

## Parse messages and statuses

Every POST has the same envelope: `object` is `whatsapp_business_account`, and each `entry[].changes[]` has a `field` and a `value`. Iterate both arrays. Meta says "POST requests are aggregated and sent in a batch with a maximum of 1000 updates", and also that "batching cannot be guaranteed", so one POST can carry one event or many.

Inbound messages sit in `value.messages[]`. In Meta's text sample, `from` is the sender, `id` is a `wamid.` string, `timestamp` is a string and the text is in `text.body` ([Meta text message webhook, accessed 2026-11-03](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text)). Meta calls `timestamp` a "Unix timestamp indicating when the webhook was triggered" without naming the unit. The 10-digit example reads as seconds. The sender's name is in `value.contacts[].profile.name`, next to a `wa_id`. Meta notes that "a WhatsApp user's ID and phone number may not always match", and [business-scoped user IDs](/academy/articles/whatsapp-usernames-business-scoped-user-ids/) covers what that means for contact tables keyed on phone.

Delivery updates for messages you sent sit in `value.statuses[]` ([Meta status webhook, accessed 2026-11-03](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/status)). Each has the message `id`, a `status`, a `timestamp` and a `recipient_id`. A `failed` status adds an `errors[]` array with `code`, `title`, `message`, `error_data.details` and `href`.

| `status` | Meta's description |
|---|---|
| `sent` | "Indicates the message was successfully sent from our servers." |
| `delivered` | "Indicates message was successfully delivered to the WhatsApp user's device." |
| `read` | "Indicates the message was displayed in an open chat thread in the WhatsApp user's device." |
| `failed` | "Indicates failure to send or deliver the message to the WhatsApp user's device." |
| `played` | "Indicates the first time a voice message is played by the WhatsApp user's device." |

Statuses also carry a `pricing` object with `billable`, `pricing_model` and `category`, which [reading Meta's rate card](/academy/articles/whatsapp-api-pricing-by-country-rate-card/) puts to use. From v24.0 on, Meta omits the `conversation` object except on free entry point webhooks. [Status webhooks](/academy/articles/whatsapp-message-status-webhooks-sent-delivered-read-failed/) covers each state in detail.

## Deduplicate retries

Retries "can result in duplicate webhook notifications", and Meta's endpoint guide says "Your server should handle deduplication in these cases." The server keys messages on `id` and statuses on `id` plus `status`, since one message ID legitimately arrives as `sent`, then `delivered`, then `read`. The in-memory `Set` resets on restart and grows without bound. Replace it with a unique index in your database.

Don't rely on arrival order either. Meta's send guide says "the order in which messages are delivered is not guaranteed" ([Meta send messages, accessed 2026-11-03](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages)). Its webhook pages make no ordering promise either. [Out-of-order webhooks](/academy/articles/whatsapp-webhooks-out-of-order-message-sequencing/) covers sequencing.

## Test it with a signed request

This sends Meta's text webhook sample, compacted to one line, with a signature computed from your app secret.

```bash
cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST http://localhost:3000/webhook \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary @sample.json
```

The first run returns 200 and logs the message. The second run returns 200 and logs nothing, because the ID is already in the set. Change one character in `sample.json` without re-signing and the server returns 401. Use `--data-binary` so curl sends the file bytes unchanged.

*Z-API Omni team*
