DEV Community

Cover image for Verifying webhook signatures in Node.js: raw body, HMAC, timingSafeEqual and replay protection
Sushil Barwal
Sushil Barwal

Posted on

Verifying webhook signatures in Node.js: raw body, HMAC, timingSafeEqual and replay protection

Webhooks are how payment providers, Git hosts, CRMs and e-commerce platforms tell your backend that something happened. They are also an open door: anyone who finds your webhook URL can send it a POST request. Signature verification is what separates "GitHub says a push happened" from "someone on the internet says a push happened".

Most providers use the same idea. They share a secret with you, compute an HMAC of the request body with that secret, and send the result in a header. Your job is to compute the same HMAC and compare. It sounds like five lines of code, and it is, but there are five details that break it in real projects. This tutorial walks through each one with Express and Node's built-in crypto module.

1. Keep the raw body

The signature is computed over the exact bytes the provider sent. If a JSON body parser runs first, you get a JavaScript object, and JSON.stringify(req.body) will not reproduce the original bytes (key order, whitespace and number formatting can all differ). The HMAC will not match, and someone will "fix" it by disabling verification.

In Express, use express.raw() on the webhook route only, so the rest of your API keeps using JSON parsing:

import express from "express";

const app = express();

// Webhook route: keep the body as a Buffer
app.post(
  "/webhooks/github",
  express.raw({ type: "application/json", limit: "1mb" }),
  handleGithubWebhook
);

// Everything else: normal JSON parsing
app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

Order matters: if app.use(express.json()) is registered before the webhook route, the body is already consumed by the time your handler runs.

2. Compute the HMAC the way the provider documents it

GitHub, for example, sends an X-Hub-Signature-256 header containing sha256= followed by the hex HMAC-SHA256 of the raw body, using the secret you configured for the webhook:

import crypto from "node:crypto";

function expectedGithubSignature(rawBody, secret) {
  const digest = crypto
    .createHmac("sha256", secret)
    .update(rawBody)
    .digest("hex");
  return `sha256=${digest}`;
}
Enter fullscreen mode Exit fullscreen mode

Other providers vary in small ways: some sign timestamp + "." + body instead of the body alone, some use base64 instead of hex, some send several signatures during secret rotation. Read the provider's webhook security page and follow it exactly. Do not guess.

3. Compare with timingSafeEqual, and check the length first

A normal string comparison (===) can return as soon as it finds the first different character. In theory, an attacker who can measure response times precisely can use that to guess a valid signature one character at a time. crypto.timingSafeEqual takes the same time regardless of where the buffers differ.

It has one trap: it throws if the two buffers have different lengths. Check the length yourself and treat a mismatch as an invalid signature:

function safeEqual(a, b) {
  const bufA = Buffer.from(a, "utf8");
  const bufB = Buffer.from(b, "utf8");
  if (bufA.length !== bufB.length) return false;
  return crypto.timingSafeEqual(bufA, bufB);
}

function handleGithubWebhook(req, res) {
  const received = req.get("X-Hub-Signature-256") || "";
  const expected = expectedGithubSignature(req.body, process.env.GITHUB_WEBHOOK_SECRET);

  if (!safeEqual(received, expected)) {
    return res.status(401).send("invalid signature");
  }
  // ...continue
}
Enter fullscreen mode Exit fullscreen mode

Return a plain 401 without explaining which part failed. Log the details on your side instead.

4. Reject old requests (replay window)

A valid signed request stays valid forever if you only check the signature. If an attacker captures one (from a log, a proxy or a misconfigured debugging tool), they can send it again. Providers that include a timestamp in the signed payload let you reject requests older than a few minutes:

const TOLERANCE_SECONDS = 300;

function isFresh(timestampSeconds) {
  const now = Math.floor(Date.now() / 1000);
  return Math.abs(now - Number(timestampSeconds)) <= TOLERANCE_SECONDS;
}
Enter fullscreen mode Exit fullscreen mode

Only use a timestamp that is part of the signed data. A timestamp in an unsigned header can be changed by whoever replays the request. If your provider does not sign a timestamp, the next step (idempotency) is your main protection against duplicates.

5. Make the handler idempotent

Providers retry. If your endpoint times out or returns a 5xx, the same event will arrive again, sometimes minutes later, sometimes several times. Most providers send a unique delivery or event ID (GitHub uses the X-GitHub-Delivery header). Store it and skip events you have already processed:

async function handleOnce(deliveryId, work) {
  // A unique index on delivery_id makes this safe under concurrency
  const inserted = await db.query(
    "INSERT INTO webhook_deliveries (delivery_id) VALUES ($1) ON CONFLICT DO NOTHING RETURNING delivery_id",
    [deliveryId]
  );
  if (inserted.rowCount === 0) return "duplicate";
  await work();
  return "processed";
}
Enter fullscreen mode Exit fullscreen mode

The unique constraint matters more than the SELECT-then-INSERT pattern you might write first: two retries can arrive at the same moment, and only a database constraint stops both from running.

Bonus: respond fast, work later

Webhook providers expect a quick 2xx. If the work is slow (calling other APIs, generating PDFs, syncing orders), verify the signature, record the event, return 200, and process it in a background job. This also keeps your Node.js event loop free for other requests, which is the single most useful habit for any Node.js API.

Checklist

  • Raw body on the webhook route only, registered before the JSON parser.
  • HMAC computed exactly as the provider documents it.
  • timingSafeEqual with a length check first.
  • A replay window when the provider signs a timestamp.
  • Idempotency keyed on the delivery or event ID, enforced by a unique index.
  • Quick 2xx, slow work in a background job.
  • The secret in an environment variable or secret manager, never in the repository, and a plan for rotating it.

FAQ

Why not just restrict the webhook to the provider's IP addresses?
IP allow-lists are a useful extra layer where a provider publishes its ranges, but ranges change and proxies complicate them. Signature verification works wherever your code runs, so treat it as the primary check.

Can I verify the signature after express.json() has parsed the body?
Not reliably. Use express.raw() for the webhook route, or a verify callback in the JSON parser that stores the raw buffer, so the HMAC is computed over the original bytes.

What status code should I return for an invalid signature?
A 4xx such as 401 or 400. Do not return 2xx, or the provider will think the delivery succeeded, and do not explain which check failed.

This is the kind of plumbing we write for client APIs and integrations at Dzimark. If you are planning a backend with several third-party integrations, our custom software development team can help with the architecture or the build.

Top comments (1)

Collapse
 
sunnatulla_dev profile image
Sunnatulla •

One catch in handleOnce: the id is stored before work() runs. I made work throw once (a CRM timeout), the handler returned 500, and both retries came back "duplicate", so the event was never processed. Deleting the row in a catch, or doing the insert and the work in one transaction, fixes it.