Cluster 14 · Node.js Backend · express.raw() + 429

Express express.raw() Webhook Verification, Retry-After 429s & Idempotency Store

Fix the classic Express `express.json()` raw-body trap by mounting `express.raw({ type: 'application/json' })` before JSON middleware, plus timing-safe HMAC and RFC 429 headers.

100% Browser-Side · WebCrypto crypto.subtle · Strict CSP

1. Webhook Signature & Replay-Window Inputs

crypto.subtle HMAC-SHA256
Paste an incoming signature header to run constant-time verification.
Replay-Window & Clock-Skew Gate
42s age vs 300s max
PASS: WITHIN REPLAY WINDOW
Event age 42s is within <=300s tolerance window (258s remaining). Pair with Idempotency/Delivery ID cache. (126 UTF-8 bytes · Stripe signs `${t}.${rawBody}` with HMAC-SHA256 hex and enforces a 300-second default replay window.)
Computed HTTP Signature Header
Stripe-Signature: t=1795705200,v1=1c60a68742c053b3f0e262e2023bb7e9259b0db8e053a17857a45e79ff5aea39
HMAC-SHA256 Hex
1c60a68742c053b3f0e262e2023bb7e9259b0db8e053a17857a45e79ff5aea39
HMAC-SHA256 Base64
HGCmh0LAU7Pw4mLiAju36SWbDbjgU6F4V6Reef9a6jk=
Drop-In WebCrypto Verifier + Replay Guard (verifyWebhook.ts)
// Strict WebCrypto Webhook Verifier + Replay Guard (Cloudflare Workers / Node 20+)
const REPLAY_TOLERANCE_SEC = 300;

function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
  return diff === 0;
}

export async function verifyWebhookRequest(request: Request, secret: string): Promise<{ ok: boolean; reason: string; rawBody: string }> {
  const rawBody = await request.text();
  const sigHeader = request.headers.get("stripe-signature") || "";
  const parts = Object.fromEntries(sigHeader.split(",").map((p) => p.split("=")));
  const ts = Number(parts.t || 0);
  const nowSec = Math.floor(Date.now() / 1000);
  if (!ts || nowSec - ts > REPLAY_TOLERANCE_SEC || ts - nowSec > 30) return { ok: false, reason: "replay_window_rejected", rawBody };
  const signedInput = `${ts}.${rawBody}`;
  const providedHex = (parts.v1 || "").toLowerCase();
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(signedInput)));
  const expectedHex = [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
  const ok = timingSafeEqual(enc.encode(providedHex), enc.encode(expectedHex));
  return { ok, reason: ok ? "verified" : "invalid_signature", rawBody };
}
WebhookSLA Guard · Live Check $29 WebhookSLA Guard Kit

Verify Live Webhook Replay Defense, 429 Retry-After & DLQ SLA Readiness

Run a live webhook endpoint & SLA audit on WebhookSLA Guard (webhook.runglab.dev), grab the turnkey $29 WebhookSLA Guard Kit (WebCrypto HMAC verifiers, replay-window store, RFC RateLimit-* middleware & DLQ runbooks) on Creem, or audit webhook OpenAPI specs on SpecDiff (spec.runglab.dev). Need a PayPal invoice? Email [email protected].

Webhook SLA, Signature & Retry Specification Matrix

Control / Header Production Baseline Reliability & Security Rationale
Middleware Order express.raw() BEFORE express.json() Global `app.use(express.json())` strips raw body access unless route-isolated or verify-hooked
Signature Compare crypto.timingSafeEqual(bufA, bufB) Verify equal byte lengths prior to timingSafeEqual to prevent RangeError crashes
Replay & Idempotency Timestamp <= 300s + eventId cache Guard both stale timestamp replay and duplicate redeliveries
Throttle Headers RateLimit-Policy + RateLimit + Retry-After Send clean 429 cooldown hints during traffic spikes

Express Route-Scoped express.raw() + Replay Verifier

express-webhook-route.mjs
import crypto from "node:crypto";
import express from "express";

const app = express();

// Mount express.raw() BEFORE global express.json()!
app.post("/webhooks/stripe", express.raw({ type: "application/json" }), (req, res) => {
  const sig = String(req.headers["stripe-signature"] || "");
  const parts = Object.fromEntries(sig.split(",").map((kv) => kv.split("=")));
  const ts = Number(parts.t || 0);
  const now = Math.floor(Date.now() / 1000);
  if (!ts || now - ts > 300 || ts - now > 30) {
    return res.status(400).json({ error: "replay_window_rejected" });
  }
  const signed = Buffer.concat([Buffer.from(`${ts}.`, "utf8"), req.body]);
  const expected = crypto.createHmac("sha256", process.env.WEBHOOK_SECRET || "").update(signed).digest("hex");
  const provided = String(parts.v1 || "").toLowerCase();
  if (provided.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(expected))) {
    return res.status(401).json({ error: "invalid_signature" });
  }
  return res.status(200).json({ ok: true });
});

app.use(express.json());

Express 429 RateLimit-* + Retry-After Middleware

express-ratelimit-headers.mjs
export function sendRateLimited(res, policyName, limit, windowSec, retryAfterSec) {
  res.set({
    "RateLimit-Policy": `"${policyName}";q=${limit};w=${windowSec}`,
    "RateLimit": `"${policyName}";r=0;t=${retryAfterSec}`,
    "Retry-After": String(Math.max(1, retryAfterSec)),
    "Cache-Control": "no-store"
  });
  return res.status(429).json({ error: "rate_limited", retryAfterSec });
}

Implementation Steps & Key Insights

  1. Register `app.post('/webhooks/...', express.raw({ type: 'application/json' }))` BEFORE any global `app.use(express.json())`.
  2. Verify `Buffer.isBuffer(req.body)` so signature validation fails loudly if middleware order is ever misconfigured.
  3. Check timestamp tolerance (`<= 300s`), run `crypto.timingSafeEqual`, and deduplicate event IDs before mutating state.
  4. Emit `RateLimit-Policy`, `RateLimit`, and `Retry-After` headers whenever rate limiting returns `429`.
  • Mounting `app.use(express.json())` at the top of `server.js` is the single most common cause of Express Stripe/GitHub/Shopify webhook failures.
  • Alternatively, if using global `express.json({ verify: (req, res, buf) => { req.rawBody = buf; } })`, store `req.rawBody` cleanly without mutating encoding.
  • Never leak stack traces or expected HMAC values in 401 responses.

Common Production Pitfalls

  • Mounting `express.json()` before webhook routes, converting `req.body` into a parsed JS object.
  • Passing a non-Buffer string into `req.body` or forgetting `Buffer.from(..., 'utf8')` byte lengths.
  • Throwing unhandled `RangeError` from `timingSafeEqual` when an attacker sends a 1-byte signature header.
Ship Faster: Audit your live endpoint on webhook.runglab.dev or grab the $29 WebhookSLA Guard Kit.

More Enterprise Webhook SLA & Signature Guides

← Back to Webhook SLA Kit Hub · WebhookSLA Guard ($29 Kit) → · SpecDiff OpenAPI Audit → · Cluster 7B: CORS & HMAC → · Cluster 9: OpenAPI OWASP →

Frequently Asked Questions

Can I use `express.json({ verify })` instead of route-level `express.raw()`?

Yes — `express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })` preserves the raw `Buffer` before JSON parsing while keeping `req.body` parsed.

Why must I verify `provided.length === expected.length` before `crypto.timingSafeEqual`?

`crypto.timingSafeEqual` throws an uncaught `RangeError` if the two buffers have different lengths, which can turn invalid probes into 500s.

Where can I test my Express webhook SLA compliance live?

Audit your live webhook endpoint on https://webhook.runglab.dev or purchase the $29 WebhookSLA Guard Kit for drop-in middleware.