Verify webhook signatures in Node.js: HMAC-SHA256, timestamps and replays

How to verify a webhook signature in Node.js: parse t= and v1=, HMAC-SHA256 the raw body, compare in constant time, reject old timestamps, handle rotation.

Published
Reading time
8 min read
By
ExtractHub team
  • webhooks
  • Node.js
  • security
  • HMAC
  • Batch API
On this page

A webhook endpoint is a public URL that accepts POST requests from anyone. Before your code marks a batch as done or downloads its results, it has to know the request really came from the sender and is not a replay of an old one. That is what the signature header is for, and this post shows how to verify a webhook signature in Node.js, step by step, for the webhooks ExtractHub sends when a batch or an async job finishes.

The scheme is the common “timestamp plus HMAC” design, so most of what follows applies to other senders that sign the same way. Where details matter (which bytes are signed, how the secret is used, how rotation looks), they are taken from ExtractHub’s sender code.

What ExtractHub signs and sends

Batches and async jobs send a JSON POST for these events: batch.completed, batch.failed, batch.paused, job.completed and job.failed, plus webhook.test from the “Send test event” button. You set the URL per request (webhook_url) or once as an account default webhook on the API keys page. The Batch API walkthrough covers when each event fires.

The body is small on purpose. It carries ids, status, counts, the cost charged, your metadata and links, never result data:

{
  "id": "evt_...",
  "type": "job.completed",
  "created_at": "2026-10-30T12:00:00.000Z",
  "data": {
    "job_id": "job_...",
    "status": "completed",
    "counts": { "total": 1, "succeeded": 1, "failed": 0, "cancelled": 0, "pending": 0 },
    "cost": 0.002,
    "status_url": "...",
    "result_url": "...",
    "metadata": null
  }
}

Four headers come with it:

  • X-Webhook-Id: the event id (evt_...), the same on every delivery attempt of that event.
  • X-Webhook-Event: the event type.
  • X-Webhook-Attempt: 1 for the first delivery, then 2, 3 and so on.
  • X-Webhook-Signature: t=<unix seconds>,v1=<hex>.

The v1 value is HMAC-SHA256, as lowercase hex, of the string <t>.<raw body>, keyed with your webhook signing secret. Signing the timestamp together with the body means an attacker cannot take an old signed request and change its t to make it look fresh.

The signing secret looks like whsec_ followed by 64 hex characters. It belongs to your account, not to an API key, so live and sandbox events use the same secret. You reveal, copy and rotate it on the API keys page.

How to verify a webhook signature in Node.js

The check has four parts:

  1. Parse the header into the timestamp t and every v1 value (there can be two, see rotation below).
  2. Reject the request if t is more than five minutes away from your clock.
  3. Compute HMAC-SHA256 of `${t}.` followed by the raw body bytes, keyed with the full secret string.
  4. Accept if any v1 equals your result, compared in constant time.

With node:crypto it fits in one function:

// verify-webhook.js
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 300;

export function verifyWebhookSignature(secret, header, rawBody, now = Math.floor(Date.now() / 1000)) {
  if (!header) return false;

  let timestamp = NaN;
  const signatures = [];
  for (const part of header.split(",")) {
    const [key, value] = part.trim().split("=");
    if (key === "t") timestamp = Number(value);
    else if (key === "v1" && value) signatures.push(value);
  }
  if (!Number.isInteger(timestamp) || signatures.length === 0) return false;
  if (Math.abs(now - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", secret)
    .update(`${timestamp}.`)
    .update(rawBody) // Buffer or string, exactly as received
    .digest();

  return signatures.some((signature) => {
    const received = Buffer.from(signature, "hex");
    return received.length === expected.length && timingSafeEqual(received, expected);
  });
}

A few choices in that code are deliberate:

  • The secret is used as text. The key is the whole whsec_... string, UTF-8 encoded, prefix included. Some webhook libraries assume a whsec_ secret is base64 and decode it before use; with ExtractHub’s secret that produces a different key and every check fails. Write the dozen lines yourself or check what your library does with the secret.
  • The comparison works on bytes. timingSafeEqual throws when the buffers differ in length, hence the length check first. A malformed hex value decodes to a shorter buffer and is simply rejected.
  • now is a parameter. That makes the function easy to unit-test with a fixed clock.

The five-minute tolerance is the same window the dashboard and the API reference recommend. Keep your server clock synced: a host that drifts by minutes rejects valid events.

Keep the raw body: an Express receiver

The most common reason a correct secret still fails is the body. If a JSON parser runs first, you no longer have the bytes that were signed; JSON.stringify(req.body) can differ in key order, spacing or number formatting, and the HMAC changes completely. In Express, use express.raw on the webhook route and make sure no global express.json() consumes the body before it:

// server.js
import express from "express";
import { verifyWebhookSignature } from "./verify-webhook.js";

const app = express();
const secret = process.env.EXTRACTHUB_WEBHOOK_SECRET; // whsec_...

app.post("/webhooks/extracthub", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verifyWebhookSignature(secret, req.get("X-Webhook-Signature"), req.body)) {
    return res.status(400).send("invalid signature");
  }

  const eventId = req.get("X-Webhook-Id");
  if (await alreadyProcessed(eventId)) return res.sendStatus(200);

  const event = JSON.parse(req.body.toString("utf8"));
  await enqueueForProcessing(event); // your job queue; do the slow work there
  await markProcessed(eventId);
  res.sendStatus(200);
});

app.listen(3000);

alreadyProcessed, markProcessed and enqueueForProcessing stand for your own storage and queue. Three rules shape this handler.

Answer fast. Any 2xx counts as delivered. A non-2xx status, a redirect or no answer within 10 seconds counts as a failure. Do the expensive part (downloading results from results_url or result_url with your API key, writing to your database) after you answered, in a queue or background worker.

Deduplicate on X-Webhook-Id. Failed deliveries are retried up to 6 attempts over about 24 hours, after 1 minute, 10 minutes, 1 hour, 4 hours and 18 hours. If your handler did its work but the answer timed out, the same event arrives again with the same id. Keep processed ids for longer than the retry window, for example in a table with a unique constraint.

Retries are signed again. Each attempt carries a fresh t, so an event delivered 18 hours late still passes the five-minute check. You do not need to widen the tolerance to survive an outage on your side.

Two delivery details often surprise people. Redirects are never followed, so a URL that answers 301 (http to https, a missing trailing slash, a login page) fails every time. And the URL must be https on a public host; private, loopback and link-local addresses are refused when you set the URL and checked again before each delivery.

The same check with Web Crypto (Workers, Deno, Bun, Node 20+)

On runtimes with the Web Crypto API, and in route handlers that give you a standard Request, use crypto.subtle.verify. It compares the HMAC for you, in constant time:

const encoder = new TextEncoder();

function hexToBytes(hex: string): Uint8Array | null {
  if (!/^[0-9a-f]{64}$/.test(hex)) return null;
  const bytes = new Uint8Array(32);
  for (let i = 0; i < 32; i++) bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
  return bytes;
}

export async function verifyWebhook(secret: string, header: string | null, rawBody: string): Promise<boolean> {
  if (!header) return false;
  const parts = header.split(",").map((part) => part.trim().split("="));
  const t = Number(parts.find(([key]) => key === "t")?.[1]);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > 300) return false;

  const key = await crypto.subtle.importKey(
    "raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"],
  );
  const data = encoder.encode(`${t}.${rawBody}`);
  for (const [name, value] of parts) {
    const signature = name === "v1" ? hexToBytes(value) : null;
    if (signature && (await crypto.subtle.verify("HMAC", key, signature, data))) return true;
  }
  return false;
}

// In a handler: read the text first, parse after the check
// const raw = await request.text();
// if (!(await verifyWebhook(env.WEBHOOK_SECRET, request.headers.get("X-Webhook-Signature"), raw))) {
//   return new Response("invalid signature", { status: 400 });
// }
// const event = JSON.parse(raw);

request.text() returns the body as sent, and encoding it again as UTF-8 gives back the signed bytes. Call request.json() only after the check, or parse the string you already have.

Rotate the secret without dropping events

Rotate the secret when it may have leaked, or on a schedule. The “Rotate” button on the API keys page creates a new secret, and for the next 24 hours every event is signed with both: the header then looks like t=...,v1=<new>,v1=<previous>. Both functions above already accept the event if any v1 matches, so the procedure is:

  1. Rotate and copy the new secret.
  2. Deploy your receiver with the new secret. Until it is live, the old secret still matches the second v1.
  3. After 24 hours only the new secret signs.

If you run several receivers that you cannot update at the same moment, let each one accept a list of secrets during the switch and check the header against each. Do not skip the deploy: once the 24 hours are over, a receiver with the old secret rejects everything.

Test your receiver before the first real batch

First, unit-test the function by signing a body yourself with the same rule:

import { createHmac } from "node:crypto";
import { verifyWebhookSignature } from "./verify-webhook.js";

const secret = "whsec_" + "0".repeat(64); // a dummy secret for tests
const body = JSON.stringify({ id: "evt_test", type: "webhook.test", created_at: new Date().toISOString(), data: { message: "local test" } });
const t = Math.floor(Date.now() / 1000);
const v1 = createHmac("sha256", secret).update(`${t}.${body}`).digest("hex");

console.log(verifyWebhookSignature(secret, `t=${t},v1=${v1}`, body));        // true
console.log(verifyWebhookSignature(secret, `t=${t},v1=${v1}`, body + " "));  // false: body changed
console.log(verifyWebhookSignature(secret, `t=${t - 600},v1=${v1}`, body));  // false: timestamp too old

Then test the real thing end to end. Save your URL as the account default webhook on the API keys page and press “Send test event”. It sends one signed webhook.test event right away, with data.message set, and shows the result; there is no retry, and you can send up to 5 test events per minute. The “Recent webhook deliveries” table on the same page lists the last 20 attempts with the HTTP status, the error and the duration, which is the quickest way to see a redirect or a timeout.

For a full run without spending credit, submit a batch or job with a test API key (exth_test_...). Sandbox webhooks are real requests signed with your secret, and their data carries sandbox: true. The web scraping sandbox post shows how to force the failed and paused paths.

Pipeline webhooks use a different header

Pipelines have their own webhook settings in the pipeline builder, with an optional secret you choose. Their signature keeps an older format: X-Webhook-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body alone, keyed with that pipeline secret. The check is the same minus the timestamp: strip sha256=, compute the HMAC over the raw body, compare in constant time. With no timestamp in the signature there is no freshness check, so deduplicate events on your side. The list and detail pipeline post covers building the pipeline itself.

A short checklist

  • Hash the raw body, never a re-serialized object.
  • Use the full whsec_... string as the key, as text.
  • Compare bytes in constant time, and accept any of the v1 values.
  • Reject timestamps more than five minutes away, and keep your clock synced.
  • Answer 2xx within 10 seconds, without redirects, and do the work afterwards.
  • Deduplicate on X-Webhook-Id.

The headers, events and retry schedule are also listed in the API reference, next to the batch and job endpoints that send them.

FAQ

How do I verify a webhook signature in Node.js?

Read the raw request body, split the X-Webhook-Signature header into the timestamp t and one or more v1 values, compute HMAC-SHA256 of "<t>.<raw body>" with your signing secret, and accept the event if one v1 matches in a constant-time compare and t is within five minutes of now.

Why does my webhook signature never match?

Almost always because the body was parsed and serialized again before hashing, so the bytes differ from what was signed. Hash the raw body exactly as received, and use the whole whsec_ secret as text, without stripping or decoding the prefix.

What happens if my webhook endpoint is down?

A failed delivery (non-2xx answer, redirect or no answer within 10 seconds) is retried up to 6 attempts over about 24 hours. Every attempt carries the same X-Webhook-Id, so deduplicate on it.

How do I rotate a webhook signing secret without losing events?

Rotate it on the API keys page. For 24 hours every event is signed with both the new and the previous secret, so the header carries two v1 values; update your receiver to the new secret within that window.

All posts