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:
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.
1Mount the Raw-Body Webhook Route BEFORE app.use(express.json())
src/server.tsRegister /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.tstypescriptimport 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());2Alternative: Preserve req.rawBody Globally via express.json verify Hook
src/middleware/rawBodyJson.tsIf 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.tstypescriptimport 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); } }, });3Guard crypto.timingSafeEqual Against Different Buffer Lengths
src/utils/timingSafe.tsNode's crypto.timingSafeEqual throws RangeError if the attacker sends a shorter or longer signature string. Always verify equal byte lengths first.
src/utils/timingSafe.tstypescriptimport 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); }4Test With Stripe CLI Against Express Port 4000
terminalForward live test events to Express and confirm req.body arrives as a Buffer (Buffer.isBuffer(req.body) === true).
terminalbashstripe 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.
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.
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.
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.
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:
Validate Node.js dotenv and native --env-file .env configs in your browser. Fix unquoted # truncation, duplicate keys, multiline PEM keys, and NODE_ENV bugs.
Generate a production Nginx reverse proxy for Node.js Express and PM2 on port 4000 with trust proxy, real client IP headers, Certbot SSL, and rate-limit safety.
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: ..".
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →GitHub Webhook X-Hub-Signature-256 Verification in Node.js Express
Verify GitHub X-Hub-Signature-256 HMAC-SHA256 webhooks in Express.js using raw Buffers, sha256= prefix validation, and crypto.timingSafeEqual.
Stripe Webhook Verification in Next.js App Router (request.text() Guide)
Fix Stripe webhook signature mismatch in Next.js App Router Route Handlers. Use await request.text() instead of request.json() with timingSafeEqual.
Stripe Webhook Signature Verification in Laravel (Raw Body & CSRF Fix)
Fix Stripe SignatureVerificationException in Laravel 11/12 using $request->getContent(), CSRF exclusion in bootstrap/app.php, hash_equals, and async queues.
Stripe Webhook Signature Verification in FastAPI (request.body() Guide)
Fix Stripe webhook signature errors in Python FastAPI. Read raw bytes with await request.body() before Pydantic parsing and compare via hmac.compare_digest.