Verify webhooks
A dependency-free Node.js function that checks a webhook's signature and timestamp.
Requests follow Standard Webhooks, so any of its official
libraries can verify them. If you would rather not add a dependency, the function below uses only
node:crypto. It:
- recomputes the HMAC-SHA256 signature from the raw body and your
whsec_…secret, - compares signatures in constant time (
timingSafeEqual), - accepts the request if any signature in the header matches, which covers the 24 hours after a secret rotation,
- refuses a
webhook-timestampmore than 5 minutes from your clock, so old requests cannot be replayed.
It is tested against the reference vector published with the Standard Webhooks specification. The
code and its test are in the docs repository under examples/webhooks/.
// Verify a Bhakti Baazar Seller API webhook (Standard Webhooks signing).
// Plain Node.js (18+), no dependencies. Copy this file into your project.
import { createHmac, timingSafeEqual } from 'node:crypto';
const SECRET_PREFIX = 'whsec_';
const DEFAULT_TOLERANCE_SECONDS = 5 * 60;
export class WebhookVerificationError extends Error {
constructor(message) {
super(message);
this.name = 'WebhookVerificationError';
}
}
function readHeader(headers, name) {
if (typeof headers?.get === 'function') return headers.get(name) ?? undefined; // Fetch API Headers
const value = headers?.[name] ?? headers?.[name.toLowerCase()];
return Array.isArray(value) ? value[0] : value; // Node.js IncomingMessage headers
}
function signingKey(secret) {
if (typeof secret !== 'string' || !secret.startsWith(SECRET_PREFIX)) {
throw new WebhookVerificationError('The signing secret must start with whsec_');
}
return Buffer.from(secret.slice(SECRET_PREFIX.length), 'base64');
}
/**
* Checks a webhook and returns its parsed body.
*
* @param {string | string[]} secret The endpoint's `whsec_…` signing secret. Pass an
* array to accept more than one (for example while you switch to a rotated secret).
* @param {Headers | Record<string, string | string[] | undefined>} headers The request headers.
* @param {string | Buffer} rawBody The body exactly as it arrived. Do not parse and
* re-serialise JSON before verifying: any change in bytes breaks the signature.
* @param {{ toleranceSeconds?: number, now?: number }} [options] `now` is in milliseconds.
* @returns {{ id: string, type: string, created: string, data: Record<string, unknown> }}
* @throws {WebhookVerificationError} When a header is missing, the timestamp is outside
* the tolerance, or no signature matches.
*/
export function verifyWebhook(secret, headers, rawBody, options = {}) {
const { toleranceSeconds = DEFAULT_TOLERANCE_SECONDS, now = Date.now() } = options;
const id = readHeader(headers, 'webhook-id');
const timestamp = readHeader(headers, 'webhook-timestamp');
const signatureHeader = readHeader(headers, 'webhook-signature');
if (!id || !timestamp || !signatureHeader) {
throw new WebhookVerificationError('Missing webhook-id, webhook-timestamp or webhook-signature');
}
if (!/^\d+$/.test(timestamp)) {
throw new WebhookVerificationError('Invalid webhook-timestamp');
}
const ageSeconds = Math.floor(now / 1000) - Number(timestamp);
if (Math.abs(ageSeconds) > toleranceSeconds) {
throw new WebhookVerificationError('webhook-timestamp is outside the allowed tolerance');
}
const body = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody);
const signedContent = `${id}.${timestamp}.${body}`;
const expected = (Array.isArray(secret) ? secret : [secret]).map((s) =>
createHmac('sha256', signingKey(s)).update(signedContent).digest(),
);
// The header holds one or more space-separated `version,signature` pairs.
// After a secret rotation, both the old and the new secret sign for 24 hours.
const matched = signatureHeader.split(' ').some((pair) => {
const [version, signature] = pair.split(',');
if (version !== 'v1' || !signature) return false;
const received = Buffer.from(signature, 'base64');
return expected.some(
(digest) => digest.length === received.length && timingSafeEqual(digest, received),
);
});
if (!matched) {
throw new WebhookVerificationError('No matching signature');
}
return JSON.parse(body);
}Using it with Express
Verify before parsing: the signature covers the body's exact bytes, so read it raw.
import express from 'express';
import { verifyWebhook, WebhookVerificationError } from './verify-webhook.mjs';
const app = express();
const seen = new Set(); // use your database in production
app.post(
'/hooks/bhaktibaazar',
express.raw({ type: 'application/json' }),
(req, res) => {
let event;
try {
event = verifyWebhook(process.env.BHAKTI_BAAZAR_WEBHOOK_SECRET, req.headers, req.body);
} catch (error) {
if (error instanceof WebhookVerificationError) return res.sendStatus(400);
throw error;
}
// At-least-once delivery: skip an event you have already handled.
if (seen.has(event.id)) return res.sendStatus(200);
seen.add(event.id);
// Answer within 10 seconds; do slow work afterwards, for example from a queue.
res.sendStatus(200);
handleEvent(event);
},
);Using it with the Fetch API
In runtimes with Request objects (Next.js route handlers, Cloudflare Workers, Deno, Bun):
import { verifyWebhook } from './verify-webhook.mjs';
export async function POST(request) {
const body = await request.text();
try {
const event = verifyWebhook(process.env.BHAKTI_BAAZAR_WEBHOOK_SECRET, request.headers, body);
// …handle the event
} catch {
return new Response('Invalid webhook', { status: 400 });
}
return new Response(null, { status: 204 });
}The function needs node:crypto and Buffer, so run it in a Node.js-compatible runtime.
Testing your endpoint
POST /webhook-endpoints/{endpointId}/test sends a signed webhook.test event to your endpoint and
reports how it answered. See Webhooks.