Conecxt
Create account

Resources Insight

Receive WhatsApp messages with the API: a Node.js webhook, built and explained

No API reads a WhatsApp inbox. Meta pushes every message sent to your business number to a server you run. Here is that server in one Express file, with the parts the quick samples leave out: the signature, retries, media links that expire and customers who arrive without a phone number.

Conecxt team 13 min read

Share WhatsApp LinkedIn

The short version

  • No API reads a personal WhatsApp account or a Business app inbox. The Cloud API pushes each message sent to a business number on the platform to your HTTPS endpoint as a webhook.
  • Check X-Hub-Signature-256 against the raw request body with your app secret, answer 200 straight away, and do slow work such as downloads afterwards.
  • Meta retries failed deliveries for up to 7 days and says retries can produce duplicates, so store each message id and skip any you've already handled.
  • Media ids in webhooks expire after 7 days and the download URL after 5 minutes, so fetch files when they arrive.
  • Every incoming message has carried a business-scoped user ID since April 2026. The phone number field can be missing for customers who adopt a username, so don't key your records on it alone.

Arjun Bhat is the backend developer at a 15-person logistics startup in Bengaluru that delivers parcels for online brands. Customers already get a WhatsApp message when their parcel is out for delivery. What the ops lead wants now is the other direction: the “Reschedule” taps, the location pins for gates nobody can find, the photos of a crushed box, landing in the dispatch system instead of on one supervisor’s phone. (Arjun and his company are invented for this guide.)

His first search was “whatsapp api to read messages”, and the answers were confusing because the question has a false premise. This guide starts there, then builds the receiving side in Node.js and Express. It’s the companion to our Python guide to sending messages, which covers tokens, the test number and the send call.

Can an API read WhatsApp messages?

No API logs into a WhatsApp account and reads its chats, whether that’s a personal account or the Business app on a phone. What Meta offers is the Cloud API: every message a customer sends to a business phone number registered on the WhatsApp Business Platform is pushed to a server you choose, as a webhook.

You don’t poll and you can’t backfill. Meta’s endpoint page says “There are no APIs for fetching historical webhook data, so capture and store webhook payloads accordingly.” Whatever your server fails to store is gone.

A number that still lives in the Business app has to be connected to the platform first; Meta’s webhook list has history and smb_message_echoes fields for app numbers onboarded through a solution provider. Arjun’s number was already on the platform.

What has to be in place before the first webhook arrives?

A public HTTPS URL, a verify token you make up, your app secret, and a subscription to the messages field. Meta’s endpoint page says “Self-signed certificates are not supported.” The overview says the whatsapp_business_messaging permission is needed “for messages and calls webhooks”.

In the App Dashboard’s Configuration panel you paste the callback URL and verify token, Meta sends its GET check, and the list of fields appears. Tick messages.

The app also has to be subscribed to the Messaging account, through POST /<WABA_ID>/subscribed_apps. Meta’s partner page says you “must individually subscribe to every Messaging account for which you want to receive webhooks”, and a GET on the same edge lists the subscribed apps. When the dashboard’s test button works but real messages never arrive, check this first.

The whole receiver in one Express file

Here it is, 79 lines, Node 18 or later with Express 4.17+ or 5. It answers verification, checks the signature, replies 200, then logs each message, downloads photos and documents, and marks the message read. The Graph API version is in one constant; Meta’s media and mark-as-read pages, read on 5 November 2026, show v27.0.

// server.js: receive WhatsApp Cloud API webhooks (Node 18+, Express 4.17+ or 5)
const express = require('express');
const crypto = require('node:crypto');
const fs = require('node:fs/promises');

const { VERIFY_TOKEN, APP_SECRET, WA_TOKEN, PORT = 3000 } = process.env;
const GRAPH = 'https://graph.facebook.com/v27.0';
const seen = new Set(); // in production: a table with a unique key on the message id

const app = express();

// 1. Meta's verification request, sent when you save the Callback URL
app.get('/webhook', (req, res) => {
  const ok = req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === VERIFY_TOKEN;
  if (ok) return res.status(200).send(req.query['hub.challenge']);
  res.sendStatus(403);
});

// 2. Events: check the signature on the raw bytes (up to 3 MB), answer 200, then work
app.post('/webhook', express.raw({ type: 'application/json', limit: '3mb' }), (req, res) => {
  if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
  const expected = 'sha256=' + crypto.createHmac('sha256', APP_SECRET).update(req.body).digest('hex');
  const got = req.get('x-hub-signature-256') || '';
  const valid = got.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected));
  if (!valid) return res.sendStatus(401);
  res.sendStatus(200);
  setImmediate(() => handle(JSON.parse(req.body.toString('utf8'))).catch(console.error));
});

async function handle(body) {
  for (const entry of body.entry ?? []) {
    for (const { value } of entry.changes ?? []) {
      const phoneNumberId = value.metadata?.phone_number_id;
      for (const msg of value.messages ?? []) {
        if (seen.has(msg.id)) continue; // Meta retries, so the same message can arrive twice
        seen.add(msg.id);
        const user = msg.from_user_id;    // business-scoped user ID, always sent
        const phone = msg.from ?? null;   // can be missing once usernames roll out
        const windowEnds = new Date((Number(msg.timestamp) + 24 * 60 * 60) * 1000);
        console.log(user, phone, msg.type, describe(msg), 'reply before', windowEnds.toISOString());
        const media = msg.image ?? msg.document;
        if (media) await download(media.id);
        await markRead(phoneNumberId, msg.id);
      }
      for (const st of value.statuses ?? []) console.log('status', st.id, st.status);
    }
  }
}

function describe(msg) {
  switch (msg.type) {
    case 'text': return msg.text.body;
    case 'interactive': return (msg.interactive.button_reply ?? msg.interactive.list_reply)?.id;
    case 'button': return msg.button.payload; // quick-reply button on a template
    case 'location': return `${msg.location.latitude},${msg.location.longitude}`;
    case 'image': return msg.image.caption ?? '(photo)';
    case 'document': return msg.document.filename;
    default: return `(${msg.type} not handled yet)`;
  }
}

async function download(mediaId) {
  const auth = { Authorization: `Bearer ${WA_TOKEN}` };
  const info = await (await fetch(`${GRAPH}/${mediaId}`, { headers: auth })).json();
  const file = await fetch(info.url, { headers: auth }); // the URL works for 5 minutes
  if (!file.ok) throw new Error(`media ${mediaId}: HTTP ${file.status}`);
  await fs.writeFile(`media-${mediaId}`, Buffer.from(await file.arrayBuffer()));
}

async function markRead(phoneNumberId, messageId) {
  await fetch(`${GRAPH}/${phoneNumberId}/messages`, {
    method: 'POST',
    headers: { Authorization: `Bearer ${WA_TOKEN}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ messaging_product: 'whatsapp', status: 'read', message_id: messageId }),
  });
}

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

We ran it locally with a correctly signed payload, a wrong signature and a repeated message: 200, 401, and the repeat skipped. The seen set is the one shortcut; it forgets everything on restart.

Why the signature check needs the raw body

Meta signs the exact bytes it sent. Its endpoint page says the X-Hub-Signature-256 header is an “HMAC-SHA256 hash, calculated using the post body payload and your app secret as the secret key”. If you let express.json() parse the body first and then re-serialise it to check the hash, spacing and key order can change and the hashes stop matching. That’s why the route uses express.raw() and parses only after the check.

The limit is there for a second reason. Meta’s overview says “Webhook payloads can be up to 3 MB”, and Express’s own API reference gives the body parsers a default limit of “100kb”. A large batch would be rejected before your code saw it, which Meta counts as a failed delivery.

timingSafeEqual needs both buffers the same length, hence the length test in front of it. The app secret is under App settings, Basic; keep it out of the repository.

Where the message sits in the payload

Everything lives under entry[].changes[].value. Incoming messages are in a messages array; delivery receipts for what you sent are in a statuses array; metadata.phone_number_id says which of your numbers received it, and contacts carries the customer’s profile name. The messages reference (Updated 17 Jun 2026) says what’s in that array “can vary greatly based on message type”, so branch on type.

These are the types a first bot meets, from Meta’s per-type references:

What the customer didtypeWhere the useful value is
Typed a messagetexttext.body
Tapped a reply button you sent in the chatinteractiveinteractive.button_reply.id and .title
Picked a row from a list messageinteractiveinteractive.list_reply.id, .title, .description
Tapped a quick-reply button on a templatebuttonbutton.payload and button.text
Sent a photo or a fileimage, documentid (the media id), mime_type, caption, filename for documents
Shared a locationlocationlatitude, longitude, and name and address if a place was picked

Notice the split between interactive and button. A button on a template comes back as button; a button on a message you sent inside the chat comes back as interactive. Arjun’s “Reschedule” button lives on an approved template, so his code reads button.payload. Set the id or payload to something stable like resched_slot and never match on the visible label, which someone will reword.

A message that came from a Click-to-WhatsApp ad also carries a referral block with the ad’s id and headline. Statuses for your outgoing messages are covered in our guide to sent, delivered and read, so the code only logs them.

Answer 200 first, then expect the same message twice

Reply before you do anything slow. Meta’s endpoint page doesn’t publish a response time limit, but if a media download or a database write hangs and the connection fails, Meta treats the delivery as failed and sends it again. Anything other than a 200 does the same.

Retries are generous. The overview says Meta “retries delivery with decreasing frequency until the request succeeds, for up to 7 days”, sends them “to all apps that have subscribed to webhooks” for that Messaging account, and that “These retries can result in duplicate webhook notifications.” Batches can hold up to 1,000 updates.

So the message id is your idempotency key. Store it before acting, and make “already seen” a no-op. On a serverless host, setImmediate after the response may never run; there, put the payload on a queue and return.

A media webhook gives you an id, not a file. Meta’s media page (Updated 30 Oct 2026) describes two steps: a GET on the media id returns a URL, and a GET on that URL with your access token returns the bytes. The clocks are short. “Media URLs expire after 5 minutes”, and “Media IDs in webhooks expire after 7 days.”

If the download returns 404, Meta’s advice is to fetch a new URL and try again, and if that fails, to renew your access token. The reference pages also describe a url field inside media webhooks, “being released to developers gradually” since 12 November 2025, so don’t depend on it yet. Customers can send files up to 100 MB; anything bigger arrives as error 131052, and Meta suggests telling the customer.

For Arjun, damage photos are evidence in a dispute with a brand, so they go to the startup’s own storage on arrival, filed under the message id.

Should your code mark messages as read?

Only when someone, or something, has actually dealt with the message. Meta’s mark-as-read page (Updated 15 Oct 2026) is a POST to /<PHONE_NUMBER_ID>/messages with status: "read" and the message id. It must happen “within 30 days of receipt”, and it “also marks earlier messages in the conversation as read”.

The customer sees it. Meta’s send-messages page says marking a message read “causes two blue check marks (called ‘read receipts’) to appear below the user’s message”, so it’s a promise. Our code marks read immediately because a log line is all it does. In Arjun’s real system, a button tap that changes the delivery slot by itself can be marked read at once; a photo of a crushed box should stay unread until a person has opened it. An invalid id returns error 131009.

Customers who arrive without a phone number

Key your records on the business-scoped user ID, with the phone number as a second field that may be empty. Meta’s usernames page (Updated 23 Oct 2026) says BSUIDs “began appearing in webhooks in early April 2026” and appear in from_user_id on every incoming message.

The phone number is no longer guaranteed. Once a customer adopts a username, from and contacts[].wa_id are omitted unless your number has messaged or called them, or heard from them, in the last 30 days, or they’re in your contact book. Meta says plainly that you “must support BSUID to avoid losing the ability to process their messages”. A phone number change also regenerates the BSUID, reported as a system message with previous_user_id, so handle that type rather than letting it fall into the default branch. The contact-list side is in our piece on WhatsApp usernames.

What the arrival time means for your reply

Each customer message opens or resets a 24-hour customer service window. Inside it you can send free-form replies; Meta’s send-messages page says that when it closes, “you can only send pre-approved template messages.” The code computes the deadline from the webhook’s timestamp, which Meta describes as the time the webhook was triggered, close enough to plan around.

The deadline has a price attached. Replies inside the window are service messages: free for the first 1,000 per business number each month, then ₹0.1150 each to an Indian number before GST on the rate card effective 1 October 2026. Miss the window and a reply becomes a utility template at ₹0.1150, or a marketing one at ₹0.8631 if Meta classifies it that way, and the customer has to answer before you can type freely again. One exception: when the message came from a Click-to-WhatsApp ad on a phone, replying inside the window opens a free entry point window, which Meta says “may remain open for up to 7 days”, and Meta doesn’t charge for marketing, utility, authentication or service messages inside it. Our send-message API guide covers which reply type to use when.

The errors that eat an afternoon

Most first-day failures aren’t in the code. Check these in order:

  • Verification fails when you save the URL. The GET handler must return status 200 with the challenge string itself as the body. If it “responds with anything else”, Meta treats the endpoint as unverified, and a JSON wrapper or a redirect is something else.
  • Every POST returns 401. The body was parsed before hashing, or the app secret belongs to a different app.
  • The test button works, real messages don’t. Check subscribed_apps on the Messaging account, and that the app is in Live mode: Meta’s troubleshooting list says “some webhooks will not be sent if your app is in Dev mode.”
  • Downloads fail after a few hours. You’re on the temporary token, and Meta’s access tokens page says user tokens “expire quickly”; use a system user token, as the Python guide explains.

For local testing, a tunnelling tool gives your laptop a public HTTPS address, or you can use the test webhook app Meta’s docs describe, an Express app that logs every payload. Neither belongs in production.

Build it or not?

Build it if WhatsApp events have to change records in your own system, the way Arjun’s slot changes and damage photos must. Eighty lines of Node is the easy part; the work is the table of seen ids, a place for media, token rotation and someone who notices when the endpoint goes quiet. If the ops lead really wants supervisors to see and answer chats, that’s an inbox, and a much bigger build than a receiver. Terms such as Messaging account, BSUID and customer service window are defined in the glossary.

Arjun’s first step is small: deploy the file, save the callback URL, tap his own “Reschedule” button, and confirm the payload says button, not interactive.

Common questions

Is there a WhatsApp API to read messages?

Not for a personal account or the Business app on a phone. Meta's Cloud API sends each message customers send to a business number registered on the WhatsApp Business Platform to your server as a webhook, an HTTPS POST carrying JSON. Nothing can be fetched later: Meta says there are no APIs for historical webhook data.

How do I receive WhatsApp messages in Node.js?

Run an HTTPS endpoint, for example in Express, that answers Meta's GET verification by returning hub.challenge when hub.verify_token matches your own string. Then accept POSTs, check the X-Hub-Signature-256 header against the raw body using your app secret, reply 200, and read the messages array under entry, changes and value.

Why does my WhatsApp webhook receive the same message twice?

Because Meta retries. If your endpoint returns anything other than 200, or delivery fails for another reason, Meta retries with decreasing frequency for up to 7 days, and its webhooks page says retries can produce duplicate notifications. Store every message id you have processed and skip any id you have already seen.

How do I download an image a customer sent on WhatsApp?

Take the media id from the image block in the webhook, send a GET request for that id with your access token to get a download URL, then GET the URL with the same token. Meta says the URL expires after 5 minutes and media ids that arrive in webhooks expire after 7 days.

Sources

  1. WhatsApp webhooks overview (Meta for Developers) · Updated 26 Jun 2026, read live 5 Nov 2026
  2. Create a webhook endpoint (Meta for Developers) · Updated 17 Jun 2026, read live 5 Nov 2026
  3. Set up a test webhook app (Meta for Developers) · Updated 21 May 2026, read live 5 Nov 2026
  4. messages webhook reference (Meta for Developers) · Updated 17 Jun 2026, read live 5 Nov 2026
  5. Text messages webhook reference (Meta for Developers) · Updated 21 May 2026, read live 5 Nov 2026
  6. Interactive messages webhook reference (Meta for Developers) · Updated 3 Aug 2026, read live 5 Nov 2026
  7. Quick-reply button messages webhook reference (Meta for Developers) · Updated 17 Jun 2026, read live 5 Nov 2026
  8. Image messages webhook reference (Meta for Developers) · Updated 17 Jun 2026, read live 5 Nov 2026
  9. Location messages webhook reference (Meta for Developers) · Updated 21 May 2026, read live 5 Nov 2026
  10. System messages webhook reference (Meta for Developers) · Updated 11 Aug 2026, read live 5 Nov 2026
  11. Media (Meta for Developers) · Updated 30 Oct 2026, read live 5 Nov 2026
  12. Mark messages as read (Meta for Developers) · Updated 15 Oct 2026, read live 5 Nov 2026
  13. Business-scoped user IDs and usernames (Meta for Developers) · Updated 23 Oct 2026, read live 5 Nov 2026
  14. Manage webhooks for client accounts (Meta for Developers) · Updated 30 Jun 2026, read live 5 Nov 2026
  15. Send messages: customer service windows and read receipts (Meta for Developers) · Updated 21 May 2026, read live 5 Nov 2026
  16. Access tokens (Meta for Developers) · Updated 19 Sep 2026, read live 5 Nov 2026
  17. Pricing on the WhatsApp Business Platform (Meta for Developers) · Updated 30 Sep 2026; INR rate card effective 1 Oct 2026; read live 5 Nov 2026
  18. Express 5.x API reference: express.raw() · No date shown; read live 5 Nov 2026
Share WhatsApp LinkedIn

Get the next one

One email when something new is published. Nothing else.

Unsubscribe from any email. See our privacy policy.

Run this on your own number

Create an account, connect your WhatsApp number, and invite your team.