DEV Community

Sendaro
Sendaro

Posted on

Verifying signed webhooks in Node.js (and why you must)

A webhook endpoint is a public URL that changes your database. Anyone who finds it can curl it. If your handler trusts whatever JSON arrives, then "mark order as paid" or "this email bounced, disable the account" is one forged request away.

Most providers sign their webhooks for exactly this reason. But a signature only helps if you check it correctly, and there are a few ways to get that wrong without noticing. Your tests still pass, and the endpoint is still open.

This post covers how to verify signed webhooks in Node.js properly:

  1. How HMAC signatures work and how to check one
  2. Why you need a timing-safe comparison
  3. The raw-body trap in Express and Next.js (App Router and Pages Router)
  4. Replay protection with timestamps
  5. Making the handler idempotent

The code doesn't depend on any provider. The scheme it assumes (a hex HMAC-SHA256 over timestamp.rawBody, with the timestamp and signature in headers) is common, and it maps closely onto most providers' formats.

Why bother?

Without verification, your endpoint believes three things it has no reason to believe:

  • That the request came from your provider. Webhook URLs leak through logs, screenshots, browser history and old config.
  • That the body wasn't changed. A proxy or attacker could change "status": "bounced" to "delivered".
  • That it's new. A real, correctly signed request captured last week can be sent again today.

A signature fixes the first two. A timestamp inside the signed data fixes the third. Idempotency covers what's left, because honest providers retry, so you'll see duplicates even when nobody is attacking you.

How the signature works

You and the provider share a secret that only you two know. For every delivery, the provider computes:

signature = hex( HMAC-SHA256(secret, `${timestamp}.${rawBody}`) )
Enter fullscreen mode Exit fullscreen mode

and sends timestamp and signature as headers. You compute the same thing on your side and compare. Nobody without the secret can produce a valid signature, and changing any byte of the body or the timestamp changes the result.

Here's a verifier with no dependencies:

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

const TOLERANCE_SECONDS = 300; // 5 minutes

export function verifySignature({ rawBody, signature, timestamp, secret, now }) {
  if (!rawBody || !signature || !timestamp || !secret) return false;

  // Only accept plain integer Unix seconds.
  if (!/^\d+$/.test(timestamp)) return false;
  const ts = Number(timestamp);
  const current = now ?? Math.floor(Date.now() / 1000);

  // Too old OR too far in the future: reject before doing any crypto.
  if (Math.abs(current - ts) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", secret)
    .update(`${ts}.`)
    .update(rawBody) // Buffer or string: the exact bytes you received
    .digest("hex");

  const a = Buffer.from(expected, "utf8");
  const b = Buffer.from(signature, "utf8");
  if (a.length !== b.length) return false; // timingSafeEqual throws on unequal lengths
  return timingSafeEqual(a, b);
}
Enter fullscreen mode Exit fullscreen mode

Each check is there for a reason, so let's go through them.

Timing-safe comparison

The obvious version is expected === signature. Don't use it.

String comparison stops at the first byte that differs. A signature that's wrong in its first character gets rejected a tiny bit faster than one that's wrong in its last character. With enough requests and some statistics, an attacker can use that timing difference to recover a valid signature one character at a time. Over a real network it's hard to exploit, but it's a known attack class, and the fix costs nothing.

crypto.timingSafeEqual compares every byte no matter where the first difference is. Two details catch people out:

  • It throws if the buffers have different lengths. Check the length first and return false. Otherwise a short garbage header turns into a 500 and a stack trace in your logs. The length of a hex SHA-256 digest is public anyway (64 characters), so checking it leaks nothing.
  • Compare like with like. Here both sides are hex strings turned into UTF-8 buffers. If your provider sends a prefix (v1=...) or base64, strip or decode it first, so both buffers have the same encoding.

The raw-body trap

This is the bug I see most often. The signature covers the exact bytes the provider sent. If your framework parses the JSON before you get to it, and you then rebuild the body with JSON.stringify(req.body), you're hashing different bytes. Key order, whitespace, unicode escapes and number formatting can all change. Sometimes it matches by luck. Then a payload containing é arrives and every delivery fails.

The rule: read the raw body, verify, then parse.

Express

express.json() reads and consumes the request stream. If it's mounted globally before your webhook route, the raw bytes are gone by the time your handler runs. Mount the webhook route with express.raw() before the global JSON parser:

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

const app = express();

// 1. Webhook route first, with a raw body parser.
app.post(
  "/webhooks/email",
  express.raw({ type: "application/json", limit: "1mb" }),
  async (req, res) => {
    // If Content-Type didn't match, req.body is {} rather than a Buffer.
    if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);

    const ok = verifySignature({
      rawBody: req.body, // Buffer: hashed as-is
      signature: req.get("rf-signature"),
      timestamp: req.get("rf-timestamp"),
      secret: process.env.WEBHOOK_SECRET,
    });
    if (!ok) return res.sendStatus(401);

    const event = JSON.parse(req.body.toString("utf8"));
    await handleEvent(event);
    res.sendStatus(204);
  },
);

// 2. Everything else gets parsed JSON as usual.
app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

If you can't change the middleware order, express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }) keeps a copy of the raw bytes for every JSON route. It works, but it holds every body in memory twice, so I prefer the dedicated route.

Next.js App Router

Route handlers get a standard Request, and nothing parses the body for you. Just make sure you read it as text once and don't call request.json() first:

// app/api/webhooks/email/route.ts
import { verifySignature } from "@/lib/verify-webhook";

export async function POST(request: Request) {
  const rawBody = await request.text(); // not request.json()

  const ok = verifySignature({
    rawBody,
    signature: request.headers.get("rf-signature"),
    timestamp: request.headers.get("rf-timestamp"),
    secret: process.env.WEBHOOK_SECRET!,
  });
  if (!ok) return new Response("Invalid signature", { status: 401 });

  const event = JSON.parse(rawBody);
  await handleEvent(event);
  return new Response(null, { status: 204 });
}
Enter fullscreen mode Exit fullscreen mode

A body can only be read once. If middleware or a logging wrapper already read it, you'll get an empty string or an error. Use request.clone() in the wrapper, not in the webhook route.

Next.js Pages Router

API routes in pages/api parse JSON by default, so req.body is already an object. Turn the parser off for this route and read the stream yourself:

// pages/api/webhooks/email.ts
import type { NextApiRequest, NextApiResponse } from "next";
import { verifySignature } from "@/lib/verify-webhook";

export const config = { api: { bodyParser: false } };

async function readRawBody(req: NextApiRequest): Promise<Buffer> {
  const chunks: Buffer[] = [];
  for await (const chunk of req) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
  return Buffer.concat(chunks);
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") return res.status(405).end();

  const rawBody = await readRawBody(req);
  const ok = verifySignature({
    rawBody,
    signature: req.headers["rf-signature"] as string | undefined,
    timestamp: req.headers["rf-timestamp"] as string | undefined,
    secret: process.env.WEBHOOK_SECRET!,
  });
  if (!ok) return res.status(401).end();

  const event = JSON.parse(rawBody.toString("utf8"));
  await handleEvent(event);
  res.status(204).end();
}
Enter fullscreen mode Exit fullscreen mode

Forget bodyParser: false and the stream is already drained. readRawBody returns an empty buffer and every request fails verification. That's annoying, but at least it fails closed.

Replay protection with timestamps

A valid signature proves the provider sent this exact request at some point. It doesn't prove it was sent just now. If someone captures a signed request (from a log, a misconfigured proxy or a shared debugging session), they can send it again as often as they like, and it will verify every time.

Signing the timestamp together with the body closes that hole. The attacker can't change the timestamp without breaking the signature, so you only accept requests within a short window, usually five minutes:

  • Reject if now - timestamp > 300: too old, probably a replay.
  • Also reject if timestamp - now > 300: a timestamp in the future means a broken clock or an attempt to make a capture last longer.
  • Check the window before the HMAC. It's cheap, and you'd reject the request anyway.

Keep your server clock synced (NTP). If you're on a VM or container host that drifts, a five-minute window gives you room, but zero drift handling will eventually reject real events.

A window narrows replays. It doesn't stop them: inside those five minutes, the same request still verifies. That's where idempotency comes in.

Idempotency: assume every event arrives twice

Even without an attacker, you will get duplicates. Providers retry when you time out, return a 5xx or drop the connection after processing but before responding. Delivery is "at least once", so your handler has to be safe to run twice.

The pattern is claim, then act. Record that you've seen the event in the same atomic step that decides whether to process it:

CREATE TABLE webhook_events (
  dedupe_key  text PRIMARY KEY,
  received_at timestamptz NOT NULL DEFAULT now()
);
Enter fullscreen mode Exit fullscreen mode
async function handleEvent(event) {
  // Prefer the provider's event id. If there isn't one, derive a key from
  // fields that identify the event uniquely (e.g. object id + event type).
  const key = event.id ?? `${event.data.id}:${event.type}`;

  await db.tx(async (tx) => {
    const claimed = await tx.query(
      `INSERT INTO webhook_events (dedupe_key) VALUES ($1)
       ON CONFLICT DO NOTHING RETURNING dedupe_key`,
      [key],
    );
    if (claimed.rowCount === 0) return; // seen before: no-op, still answer 2xx

    await applyEvent(tx, event); // DB changes in the same transaction
  });
}
Enter fullscreen mode Exit fullscreen mode

Why it's built this way:

  • ON CONFLICT DO NOTHING is atomic. If two retries land at the same moment, exactly one gets the row. "SELECT, then INSERT if missing" has a race between the two steps.
  • The claim and the side effects commit together. If applyEvent throws, the claim rolls back, you return a 5xx and the provider's retry gets a clean second attempt. If you claim in one transaction and work in another, a crash in between marks the event as done when it never happened.
  • Duplicates still get a 2xx. If you answer 409 or 500 to a duplicate, the provider keeps retrying something you've already handled.
  • Side effects outside the database (sending an email, calling another API) don't fit into the transaction. Inside the transaction, write a job to an outbox table and let a worker do the work with its own idempotency key.

Keep the handler fast. Providers give you a few seconds before they count a delivery as failed, and slow handlers cause the very retries you're now deduplicating. Verify, claim, write, return 2xx. Do anything heavy in a background job.

A short checklist

  • [ ] Verify on the raw bytes, then parse.
  • [ ] timingSafeEqual, with a length check first.
  • [ ] Reject timestamps outside ±5 minutes, before computing the HMAC.
  • [ ] Return 401 on failure and log the reason without logging the secret.
  • [ ] Dedupe with an atomic insert, and return 2xx for duplicates.
  • [ ] Answer fast and move slow work to a queue.
  • [ ] Keep the secret in an env var, out of git and out of your logs.
  • [ ] Write a test that signs a payload with a known secret and checks that a changed body, an old timestamp and a wrong-length signature all fail.

That last test only takes a few lines, and it catches most regressions, especially when someone "cleans up" the middleware order later:

import { createHmac } from "node:crypto";
const body = '{"type":"email.delivered","data":{"id":"abc"}}';
const ts = String(Math.floor(Date.now() / 1000));
const sig = createHmac("sha256", "test_secret").update(`${ts}.${body}`).digest("hex");

assert(verifySignature({ rawBody: body, signature: sig, timestamp: ts, secret: "test_secret" }));
assert(!verifySignature({ rawBody: body + " ", signature: sig, timestamp: ts, secret: "test_secret" }));
assert(!verifySignature({ rawBody: body, signature: sig, timestamp: ts, secret: "test_secret", now: Number(ts) + 301 }));
Enter fullscreen mode Exit fullscreen mode

If you're using Sendaro

Disclosure: I work on Sendaro, a transactional email API. Its webhooks follow the scheme above. Each delivery carries an rf-timestamp header (Unix seconds) and an rf-signature header, which is a hex HMAC-SHA256 of the timestamp, a period and the raw body, keyed with your endpoint's signing secret. The docs say to reject anything that doesn't match or is more than 5 minutes old. Endpoints have 8 seconds to return a 2xx. Failed deliveries get up to 5 attempts with exponential backoff. Every attempt is re-signed with a fresh rf-timestamp and rf-signature, so a legitimate retry never trips the 5-minute window, and the body is byte-identical across retries.

The sendaro npm package includes a helper that does the timestamp check, the HMAC and the constant-time comparison for you:

import { verifyWebhook } from "sendaro";

const valid = verifyWebhook(
  payload, // the raw body string
  request.headers.get("rf-signature"),
  process.env.SENDARO_WEBHOOK_SECRET!,
  request.headers.get("rf-timestamp"),
);
Enter fullscreen mode Exit fullscreen mode

It takes the body as a string, so in Express pass req.body.toString("utf8") from express.raw({ type: "application/json" }). There are 7 events: email.sent, email.delivered, email.bounced, email.complained, email.rejected, email.failed and email.unsubscribed. For dedupe, data.id (the email id) plus type works for every event except email.failed, which can fire more than once for the same email. For that one, fall back to a hash of the raw body. Since retries carry identical bytes, the hash catches redeliveries:

import { createHash } from "node:crypto";

const key =
  event.type === "email.failed"
    ? `failed:${createHash("sha256").update(rawBody).digest("hex")}`
    : `${event.data.id}:${event.type}`;
Enter fullscreen mode Exit fullscreen mode

The payload format is in the webhook docs.

Whichever provider you use, the work on your side is the same: raw bytes, constant-time compare, a tight timestamp window and a handler that doesn't mind seeing an event twice.

Top comments (0)