Skip to content

Webhooks: raw body

The signature is computed over the exact bytes Meta sent. Pass the raw body bytes to parse, isValid and verifySignature: a Buffer, Uint8Array, ArrayBuffer or the unmodified body string. Never pass a re-serialized req.body (for example JSON.stringify(req.body)), because the bytes change and a valid signature fails.

Respond only after the payload parsed. Return 401 for a bad signature, and 200 for a signed payload that cannot be parsed (log it), so Meta does not retry a permanently bad payload for days.

Express:

import express from 'express';
import { WebhookHandler, WhatsAppWebhookError } from '@solvejet/whatsapp-cloud-api';
const handler = new WebhookHandler({
appSecret: process.env.WHATSAPP_APP_SECRET!,
verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!,
});
const app = express();
app.get('/webhook', (req, res) => {
const query: Record<string, string | undefined> = {};
for (const [key, value] of Object.entries(req.query)) {
if (typeof value === 'string') query[key] = value;
}
const { statusCode, body } = handler.handleVerification(query);
res.status(statusCode).type('text/plain').send(body);
});
// express.raw keeps the body as a Buffer. Do not put express.json() before this route.
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
const rawBody = req.body as Buffer;
const signature = req.get('x-hub-signature-256');
if (!handler.isValid(rawBody, signature)) {
res.sendStatus(401); // bad signature
return;
}
try {
const { messages, statuses } = handler.parse(rawBody, signature);
res.sendStatus(200);
// handle messages and statuses here, without letting one failure drop the rest
} catch (error) {
if (error instanceof WhatsAppWebhookError) {
console.error('Ignoring malformed webhook payload:', error.message);
res.sendStatus(200); // signed but unparseable: do not make Meta retry it
return;
}
console.error(error);
res.sendStatus(500);
}
});

Next.js App Router (app/api/webhook/route.ts):

import { WebhookHandler, WhatsAppWebhookError } from '@solvejet/whatsapp-cloud-api';
const handler = new WebhookHandler({
appSecret: process.env.WHATSAPP_APP_SECRET!,
verifyToken: process.env.WHATSAPP_VERIFY_TOKEN!,
});
export async function GET(request: Request) {
const query: Record<string, string | undefined> = {};
for (const [key, value] of new URL(request.url).searchParams) query[key] = value;
const { statusCode, body } = handler.handleVerification(query);
return new Response(body, { status: statusCode, headers: { 'content-type': 'text/plain' } });
}
export async function POST(request: Request) {
const rawBody = await request.arrayBuffer(); // not request.json()
const signature = request.headers.get('x-hub-signature-256') ?? undefined;
if (!handler.isValid(rawBody, signature)) {
return new Response('Unauthorized', { status: 401 });
}
try {
const { messages } = handler.parse(rawBody, signature);
// Serverless functions can stop after the response, so await the work. Settle
// every message on its own so one failure does not drop the batch.
const results = await Promise.allSettled(messages.map((message) => handleMessage(message)));
for (const result of results) {
if (result.status === 'rejected') console.error(result.reason);
}
return new Response('OK');
} catch (error) {
if (error instanceof WhatsAppWebhookError) {
console.error('Ignoring malformed webhook payload:', error.message);
return new Response('OK'); // signed but unparseable: do not make Meta retry it
}
console.error(error);
return new Response('Internal Server Error', { status: 500 });
}
}

Hono and Fastify versions are in examples/.

Independent open-source project. Not affiliated with, endorsed by or sponsored by Meta or WhatsApp. Released under the MIT licence. Source on GitHub.