The failure looked like this: every webhook from the payment provider returned 401 in production, while the same handler had passed every test in staging for weeks. The secret was right and the HMAC algorithm was right. The bytes we were hashing were not the bytes the provider signed. That is the most common way webhook signature verification fails, and it is easy to miss because the code reads as correct.

Why webhook signature verification passed in staging

An HMAC is computed over exact bytes. The provider signs the raw request body, and you must hash those same bytes. JSON is not byte-stable. Parse it and serialize it again, and key order, whitespace, unicode escapes, number formatting and trailing newlines can all change.

Our staging fixtures were the problem. We built test payloads with JSON.stringify(obj) or json.dumps(obj) and signed those strings with the test secret. Re-serializing a compact, already-canonical payload usually reproduces it exactly, so the signature matched. The real provider sent pretty-spaced JSON with escaped forward slashes and a non-ASCII character in a customer name. After a parse and stringify round trip, the output differed by a few bytes, and the HMAC differed completely.

The Node version of the bug is usually this:

app.use(express.json());           // body is parsed here
app.post('/webhooks/pay', (req, res) => {
  const mac = crypto.createHmac('sha256', secret)
    .update(JSON.stringify(req.body))   // re-serialized: wrong bytes
    .digest('hex');
  ...
});

The tests passed because both sides serialized the same way. Production failed because the provider's serializer was not ours.

Express: capture the raw body before parsing

The fix is ordering. The raw bytes must be captured before any middleware consumes the stream, and only the webhook route should pay for it. We use one of two shapes in Node.js.

For a dedicated webhook route, mount express.raw on that path before the global JSON parser:

app.post('/webhooks/pay',
  express.raw({ type: 'application/json', limit: '1mb' }),
  verifySignature,           // req.body is a Buffer here
  handleWebhook);

app.use(express.json());     // everything else, mounted AFTER

If the same app mounts express.json() globally and you cannot reorder it, use the verify hook to stash the buffer as it streams past:

app.use(express.json({
  verify: (req, _res, buf) => { req.rawBody = buf; }
}));

Two traps here. First, a body parser only runs once per request, so if express.json() is registered first, a later express.raw() sees an empty stream and req.body stays parsed. Second, a router-level app.use(express.json()) inside a sub-router still counts. When we audit a codebase, we grep for every express.json and bodyParser call and check which routes sit above or below each one.

The comparison, in constant time

With the raw buffer in hand, compare with crypto.timingSafeEqual, not ===. A plain string comparison returns at the first differing byte, which leaks timing information. The catch is that timingSafeEqual throws if the two buffers have different lengths, so check length first. That check is safe to short-circuit on because the length of a hex digest is not secret.

function verifySignature(req, res, next) {
  const given = Buffer.from(req.get('x-signature') || '', 'hex');
  const expected = crypto.createHmac('sha256', secret)
    .update(req.body)                 // Buffer, untouched
    .digest();
  if (given.length !== expected.length ||
      !crypto.timingSafeEqual(given, expected)) {
    return res.sendStatus(401);
  }
  next();
}

If the provider includes a timestamp in the signed payload, reject anything older than a few minutes. That blocks replay of a captured request and costs one comparison.

FastAPI: the same bug, a different shape

In Python the trap moves. Declare a Pydantic model as the handler parameter and FastAPI parses the body before your function runs. Calling model.model_dump_json() afterwards gives you a re-serialization with Pydantic's own key order and spacing, which is the same bug again.

Take the Request object and read the bytes first, then parse them yourself:

@app.post('/webhooks/pay')
async def pay_webhook(request: Request):
    raw = await request.body()
    given = request.headers.get('x-signature', '')
    expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(given, expected):
        raise HTTPException(status_code=401)
    event = PayEvent.model_validate_json(raw)
    ...

hmac.compare_digest is the constant-time primitive in the standard library. It accepts two strings of the same type, and it handles unequal lengths without raising. Notice the order: verify first, then validate the schema. Parsing untrusted input before authenticating it hands an attacker your parser as attack surface.

One more FastAPI detail: await request.body() caches the bytes on the request, so reading it in a dependency and again in the route is fine. If you do this in middleware instead, be aware that consuming the stream in a BaseHTTPMiddleware has historically caused downstream handlers to hang on a drained stream. A dependency on the webhook router avoids the problem.

What we standardize now

  • Raw bytes in, always. Nothing between the socket and the HMAC may parse or re-encode the body.
  • Verify before validate. Authenticate, then parse and schema-check.
  • Constant-time compare with an explicit length guard in Node and compare_digest in Python.
  • Timestamp tolerance and idempotency keys, so replays are rejected or harmless.
  • Fixtures from real captures. Record an actual provider delivery, with its headers and bytes, and replay it in tests. Hand-built payloads are what hid this bug.
  • Log the length and a hash prefix of the body on failure, never the secret or the full signature. A length mismatch between the provider's reported size and yours points straight at a rewriting layer.

Reverse proxies deserve a mention. A gateway that gunzips, normalizes line endings or re-encodes the body will break signatures the same way, and it will do so only in the environment that has the gateway. If your staging has no proxy and prod does, you have a gap that no unit test will show.

Closing thought

Bugs like this one sit in the gap between a test environment and a real one, which is where most of the code-audit work we do at orithLabs ends up. If you have a webhook handler that behaves differently across environments, or an integration you would like a second set of engineering eyes on, we are happy to look at it with you.