Webhook HMAC-SHA256 Verifier · Stripe + Express

Stripe Webhook Verification in Node.js Express (express.raw() Order Fix)

Verify and generate Stripe + Express HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·Stripe-Signature

Stripe-Signature: t=1795378346,v1=15ff7d18e1b13314f08c8cdc01328d3197968ad206b183dd18bcd69b69c3ae75

// src/routes/webhooks.ts — Express Raw Buffer Verification
// Mount BEFORE app.use(express.json()) so express.raw() receives untouched bytes!
import crypto from 'node:crypto';
import express from 'express';

const app = express();

app.post(
  '/webhooks/stripe',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const rawBody = req.body as Buffer;
    const secret = process.env.WEBHOOK_SECRET!;

    const sigHeader = String(req.headers['stripe-signature'] ?? '');
    const parsed = Object.fromEntries(sigHeader.split(',').map((p) => p.split('=')));
    const timestamp = parsed.t ?? '';
    const received = parsed.v1 ?? '';
    if (!timestamp || Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) {
      res.status(400).send('Stale Stripe timestamp');
      return;
    }
    const expected = crypto
      .createHmac('sha256', secret)
      .update(`${timestamp}.`)
      .update(rawBody)
      .digest('hex');

    const expectedBuf = Buffer.from(expected, 'utf8');
    const receivedBuf = Buffer.from(received, 'utf8');

    if (expectedBuf.length !== receivedBuf.length || !crypto.timingSafeEqual(expectedBuf, receivedBuf)) {
      res.status(400).send('Invalid Stripe webhook signature');
      return;
    }

    const payload = JSON.parse(rawBody.toString('utf8'));
    res.status(200).json({ received: true, id: payload.id ?? null });
  }
);

// Global JSON parser mounted AFTER raw webhook routes
app.use(express.json());
1. Raw Body HMAC (HEX)Valid

15ff7d18e1b13314f08c8cdc01328d3197968ad206b183dd18bcd69b69c3ae75

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

7dff035650765f2eba2d28d00141b63f711d7ba7534e0458ce2b0d1a269c980b

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

Typical Webhook Signature Verification Error (Stripe + Express)

When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in Stripe + Express, your server logs an exception matching the output below:

Server Exception / Webhook Delivery Log

Webhook Error: Webhook payload must be provided as a string or a Buffer instance representing the _raw_ request body. Are you using body-parser or express.json()?

Raw Request Stream Handling & Replay Protection in Stripe + Express

In Node.js Express applications, middleware execution order is strictly top-to-bottom; and that single architectural rule causes the most famous Stripe webhook error in the JavaScript ecosystem. When app.use(express.json()) is mounted at the top of server.ts, Express reads the entire HTTP stream, parses it into a plain JavaScript object on req.body, and leaves zero raw bytes for downstream routes.

Even if you attach express.raw({ type: "application/json" }) to your /webhooks/stripe route later in the file, express.json() has ALREADY consumed the stream before the route middleware ever runs. Stripe's SDK then immediately throws "Webhook payload must be provided as a string or a Buffer instance representing the raw request body."

There are two rock-solid solutions in Express: either mount app.post("/webhooks/stripe", express.raw({ type: "application/json" }), handler) ABOVE app.use(express.json()), OR capture the untouched raw Buffer inside the express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }) hook so every route can access both parsed JSON and raw bytes cleanly.

When verifying signatures manually without the Stripe SDK, always split Stripe-Signature on commas, enforce the 300-second timestamp replay window, compute crypto.createHmac("sha256", secret).update(`${timestamp}.`).update(rawBuffer).digest("hex"), and compare buffers using crypto.timingSafeEqual() after checking equal buffer lengths (because timingSafeEqual throws a RangeError if lengths differ!).

Use the interactive Web Crypto debugger above to compare raw Buffer signatures against re-serialized JSON.stringify(req.body) digests and copy the exact middleware-safe Express snippet.

In Express production deployments managed by PM2 or Docker Compose, keeping raw-body webhook routes cleanly isolated in a dedicated router mounted above global express.json() eliminates accidental middleware ordering regressions as teams add new routes. Add an automated integration test using Supertest that posts a pretty-printed multi-line JSON fixture with a computed Stripe-Signature header so any future refactor that breaks express.raw() fails CI immediately.

Step-by-Step Stripe + Express Webhook Verification Setup

Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.

  1. 1Mount the Raw-Body Webhook Route BEFORE app.use(express.json())

    src/server.ts

    Register /webhooks/stripe with express.raw({ type: "application/json" }) ahead of global JSON body parsing so req.body remains an untouched Node.js Buffer.

    src/server.tstypescript
    import express from 'express';
    import Stripe from 'stripe';
    
    const app = express();
    const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
    
    // MUST be mounted BEFORE app.use(express.json())
    app.post(
      '/webhooks/stripe',
      express.raw({ type: 'application/json' }),
      (req, res) => {
        const sig = req.headers['stripe-signature'];
        if (!sig || typeof sig !== 'string') {
          res.status(400).send('Missing Stripe-Signature header');
          return;
        }
    
        try {
          const event = stripe.webhooks.constructEvent(
            req.body as Buffer,
            sig,
            process.env.STRIPE_WEBHOOK_SECRET!
          );
          res.status(200).json({ received: true, id: event.id });
        } catch (err) {
          const msg = err instanceof Error ? err.message : 'Invalid signature';
          res.status(400).send(`Webhook Error: ${msg}`);
        }
      }
    );
    
    // Global JSON parser for all regular API routes goes AFTER webhooks
    app.use(express.json());
  2. 2Alternative: Preserve req.rawBody Globally via express.json verify Hook

    src/middleware/rawBodyJson.ts

    If your routes live in separate Express Router modules mounted after global middleware, attach a verify callback to express.json() to save a copy of the exact raw Buffer on req.rawBody.

    src/middleware/rawBodyJson.tstypescript
    import express, { type Request } from 'express';
    
    export interface RawBodyRequest extends Request {
      rawBody?: Buffer;
    }
    
    export const jsonWithRawBody = express.json({
      verify: (req: RawBodyRequest, _res, buf) => {
        if (req.originalUrl.startsWith('/webhooks/')) {
          req.rawBody = Buffer.from(buf);
        }
      },
    });
  3. 3Guard crypto.timingSafeEqual Against Different Buffer Lengths

    src/utils/timingSafe.ts

    Node's crypto.timingSafeEqual throws RangeError if the attacker sends a shorter or longer signature string. Always verify equal byte lengths first.

    src/utils/timingSafe.tstypescript
    import crypto from 'node:crypto';
    
    export function safeCompareHex(expected: string, received: string): boolean {
      const a = Buffer.from(expected, 'utf8');
      const b = Buffer.from(received, 'utf8');
      if (a.length !== b.length) return false;
      return crypto.timingSafeEqual(a, b);
    }
  4. 4Test With Stripe CLI Against Express Port 4000

    terminal

    Forward live test events to Express and confirm req.body arrives as a Buffer (Buffer.isBuffer(req.body) === true).

    terminalbash
    stripe listen --forward-to http://127.0.0.1:4000/webhooks/stripe
    stripe trigger payment_intent.succeeded

Common Stripe + Express Webhook Pitfalls

Avoid these three subtle production failure modes when verifying external webhook signatures.

Pitfall 1

Mounting express.json() Above the Webhook Route

Once express.json() parses the request stream, attaching express.raw() on a downstream router has zero effect because the body has already been read and replaced with a JS object.

Pitfall 2

Calling crypto.timingSafeEqual() Without Checking Buffer Lengths First

If a malformed request sends an empty or truncated Stripe-Signature header, crypto.timingSafeEqual(a, b) throws an unhandled RangeError (HTTP 500) unless a.length === b.length is checked first.

Pitfall 3

Using express.raw({ type: "application/json" }) With Custom Content-Type Charsets

Stripe sends Content-Type: application/json; charset=utf-8. Express's type: "application/json" matches charsets cleanly, whereas writing manual === string checks on Content-Type breaks.

Related Tools

Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers

Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:

Frequently Asked Questions

Why does Stripe say "payload must be provided as a string or a Buffer" in Express?
Global app.use(express.json()) parsed req.body into an object before your Stripe webhook handler ran. Move the webhook route with express.raw({ type: "application/json" }) above express.json() or capture req.rawBody in express.json's verify hook.
Does express.raw() still work if Express sits behind Nginx?
Yes. Nginx proxies raw HTTP request bytes untouched as long as Nginx does not rewrite the body. Just verify client_max_body_size in Nginx is large enough for big webhook payloads.
Should I use BullMQ or handle Stripe webhooks synchronously in Express?
Verify the signature synchronously, write the event ID into PostgreSQL/Redis for idempotency, enqueue a BullMQ job for heavy processing, and return 200 OK immediately.
How do I test Express webhook verification without an internet tunnel?
Use the Web Crypto generator above to produce a valid Stripe-Signature header for any test JSON payload and secret, then send it directly to localhost with curl -X POST -H "Stripe-Signature: ..".
Browse all 10 webhook guides →