Dev.to Security 🔐 Cybersecurity 👁 0 📖 5 min read

Verify Webhook Signatures in Node.js: Fix the Raw-Body Bug

Originally published on Extenify. To verify webhook signatures in Node.js, you hash the request body with a shared secret and compare the result to a header. It looks like five lines of code, yet the top Stripe error, "

Originally published on Extenify.

To verify webhook signatures in Node.js, you hash the request body with a shared secret and compare the result to a header. It looks like five lines of code, yet the top Stripe error, "No signatures found matching the expected signature for payload", has close to 90,000 views on Stack Overflow, and the cause is nearly always the same: you hashed the wrong bytes. Here is what to get right, and how GitHub, Stripe and Standard Webhooks (used by Polar) differ.

The signature covers bytes, not data

Anyone who knows your webhook URL can POST to it. So the provider signs each delivery with HMAC-SHA256 using a secret only you two share. You recompute the value and compare.

The catch: HMAC works on exact bytes. If your framework parses the JSON and you call JSON.stringify on it, whitespace, escapes and number formatting can change, and the check fails even though the data looks identical. In the original tests, a re-stringified Stripe payload failed the official library's check with exactly the error above.

The three schemes differ in what they sign and how they encode it:

Provider Header Signed content Encoding
GitHub X-Hub-Signature-256 raw body hex
Stripe Stripe-Signature (t=, v1=) timestamp.body hex
Standard Webhooks (Polar) webhook-id, webhook-timestamp, webhook-signature id.timestamp.body base64

If a provider ships an SDK verifier, such as Stripe's constructEvent() or Polar's validateEvent(), use it. Write your own when there is no SDK, when you want one verifier for several providers, or when you need to understand why the SDK rejects a request.

Get the raw body first

In Express, put express.raw() on the webhook route only, and register it before any global express.json(). Stripe's troubleshooting page gives the same advice. In a Next.js App Router handler, read the body as bytes and parse it yourself afterwards:

export async function POST(request) {
  const raw = Buffer.from(await request.arrayBuffer()); // not request.json()
  if (!isValid(raw, request.headers)) {
    return new Response('invalid signature', { status: 401 });
  }
  const event = JSON.parse(raw.toString('utf8'));
  return new Response(null, { status: 204 });
}

Also check what sits in front of Node. A proxy or gateway that re-encodes or trims the body breaks the signature just as a JSON parser does.

Compare in constant time

A plain === returns at the first differing character, which leaks timing. Use crypto.timingSafeEqual, but compare lengths first: it throws ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH when the buffers differ in size. The header is attacker-controlled, so without that check a short signature turns a 401 into a 500.

import { createHmac, timingSafeEqual } from 'node:crypto';

function githubOk(raw, header, secret) {
  const want = Buffer.from('sha256=' + createHmac('sha256', secret).update(raw).digest('hex'));
  const got = Buffer.from(String(header ?? ''));
  return want.length === got.length && timingSafeEqual(want, got);
}

GitHub publishes a test vector worth pinning in a unit test: secret It's a Secret to Everybody, payload Hello, World!, expected signature 757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17.

Mind the key format

Most "it never matches" bugs after the raw body are key mistakes:

  • Stripe: the key is the whole whsec_... string as text.
  • Standard Webhooks: the key is the base64-decoded part after whsec_.
  • Stripe rotation: while an old secret stays active (up to 24 hours), Stripe sends one v1 signature per secret, so accept a match on any of them. Ignore every scheme that is not v1, which blocks downgrade attacks.
  • Standard Webhooks rotation: webhook-signature can hold several space-separated entries, so try each key against each entry.

Polar added a twist. Secrets generated on or after 8 September 2026, 00:00 UTC follow Standard Webhooks. Older secrets use the full whsec_... string's UTF-8 bytes as the key. Polar SDKs 1.0.0-alpha.19 and later try both. A custom verifier that only decodes base64 keeps working for old secrets, then rejects every delivery the day you create a new one. The fix is to pass both keys and accept a match on either.

Stop replays and slow endpoints

A valid signature proves who sent a message, not that it is new. Two defences work together:

  1. Time window. The timestamp is part of what Stripe and Standard Webhooks sign, so an attacker cannot edit it. Stripe's libraries default to 5 minutes, and Stripe warns that a tolerance of 0 disables the check. Keep your server clock on NTP.
  2. Deduplication. Store the delivery or event ID (webhook-id, Stripe's event ID, GitHub's X-GitHub-Delivery) with a unique index, and answer duplicates with a 2xx so the provider stops retrying. GitHub sends no timestamp, so for GitHub this is the only replay defence.

Then answer fast. Polar times out after 10 seconds, recommends a response within 2, and disables an endpoint after 10 consecutive failed deliveries. Verify, deduplicate, enqueue, return 204, and do the real work in a background job.

Debug a mismatch in this order

  1. Print the first characters of the secret you load and compare them with the dashboard. A secret from stripe listen differs from the dashboard endpoint secret.
  2. Log Buffer.isBuffer(body). If it is an object, a parser ran first.
  3. Check the key encoding for the provider.
  4. Read headers in lowercase (req.headers['webhook-signature']).
  5. If only some deliveries fail, compare the header timestamp with your server time.
  6. Look for a proxy, CDN or middleware that changes the body.

Key takeaways

  • Hash the raw bytes, never re-serialized JSON.
  • Check lengths, then use crypto.timingSafeEqual.
  • Keys differ per provider: text for Stripe and GitHub, base64-decoded for Standard Webhooks.
  • Reject stale timestamps and deduplicate on the delivery ID.
  • Return 2xx quickly and process in the background.
  • Polar secrets created before 8 September 2026 need a different key rule, so try both.

The original guide has the complete tested verifier for all three schemes, plus replay and duplicate handling, in verifying webhook signatures in Node.js with Stripe, GitHub and Polar. If you also track app and extension store data, Extenify's cross-platform store dashboard polls Chrome, Edge, Firefox, Google Play and App Store listings for you.

Which provider's webhook signature has cost you the most debugging time, and was it the raw body, the key format or something else?

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.