Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Stripe webhooks: no signatures found matching the expected signature

Verification needs the exact bytes Stripe sent and the endpoint's own secret. Fix parser order, proxy re-encoding and edge runtime crypto.

~5 min readNode.js
#Stripe#Webhooks#Node.js#Security
A webhook payload crate entering a verification gate with an amber mismatched seal and a cyan raw body pipe

Introduction & Quick Summary

No signatures found matching the expected signature for payload is a 400 from your own handler, produced by stripe.webhooks.constructEvent. The payload arrived, the Stripe-Signature header arrived, and they do not match. Almost every occurrence has one of three causes: the body was parsed and re-serialized before verification, the endpoint secret belongs to a different endpoint, or the request passed through something that changed bytes on the way.

What to check, in the order that finds the answer fastest:

  • Verify before parsing. The verifier needs the exact bytes Stripe sent, and express.json(), bodyParser or a framework default parser hand it a re-serialized object.
  • Use the secret of that exact endpoint. Every endpoint has its own whsec_...; the CLI prints a different one from the dashboard, and test mode differs from live mode.
  • Do not trust a proxy to preserve the body. A CDN worker that re-encodes JSON, or a gateway that base64s the payload, breaks the HMAC even though the JSON looks identical.
  • Use constructEventAsync on edge runtimes. constructEvent needs synchronous crypto, which Workers and Vercel Edge do not provide.
Error textCauseFix
No signatures found matching...Body not raw, or wrong secretRaw body buffer plus the endpoint's secret
Unable to extract timestamp and signatures from headerHeader missing or renamed by a proxyForward Stripe-Signature unchanged
Timestamp outside the tolerance zoneClock skew over 5 minutes, or a replayed old eventFix NTP, or raise tolerance deliberately
No webhook payload was providedEmpty body after a parser consumed itRead the raw body first
Works in CLI, fails in productionCLI secret used in a deployed handlerCopy the endpoint secret from the dashboard

Core Mechanics, Signatures & Reproducible Setup

Stripe signs timestamp + "." + payload with HMAC-SHA256 using the endpoint secret, then sends t=...,v1=.... Verification recomputes the HMAC over the received bytes and compares with a constant-time check. Because the signature covers bytes, any transformation invalidates it: removing a newline, reordering keys, converting to an object and back.

The Node SDK exposes two calls: constructEvent(payload, header, secret) uses synchronous crypto, and constructEventAsync uses WebCrypto, which is the one that works on edge runtimes. Both expect payload as a Buffer or string.

The classic failure is a handler whose JSON middleware runs before the webhook route:

ts
import express from "express"; import Stripe from "stripe"; const app = express(); const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!); app.use(express.json()); // consumes the body first app.post("/webhook", (req, res) => { const event = stripe.webhooks.constructEvent( req.body, // already an object, and re-serialized req.headers["stripe-signature"] as string, process.env.STRIPE_WEBHOOK_SECRET! ); res.json({ received: true }); });

The response is a 400 with the SDK's hint:

text
No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?

The fix is ordering plus a raw parser scoped to the route:

ts
app.post( "/webhook", express.raw({ type: "application/json" }), (req, res) => { const signature = req.headers["stripe-signature"]; if (typeof signature !== "string") return res.status(400).send("no signature"); let event: Stripe.Event; try { event = stripe.webhooks.constructEvent( req.body, // Buffer, untouched signature, process.env.STRIPE_WEBHOOK_SECRET! ); } catch (error) { return res.status(400).send(`Webhook Error: ${(error as Error).message}`); } res.json({ received: true, type: event.type }); } ); app.use(express.json()); // everything after the webhook route

Key Comparison Table

The framework decides whether a raw body is reachable at all.

FrameworkRaw body available asTrap
Expressexpress.raw({ type: "application/json" })Global express.json() mounted first
Next.js App Routerawait request.text()Calling request.json() first
Next.js Pages RouterbodyParser: false + buffer(req)Default parser on the API route
FastifyaddContentTypeParser(..., { parseAs: "buffer" })Default JSON parser already registered
Cloudflare Workersawait request.text()No constructEvent, use the async variant
AWS Lambda (API Gateway)event.body, base64 when binaryDecoding with the wrong charset

The secret is its own axis: every dashboard endpoint has a distinct whsec_..., the stripe listen CLI prints another for local forwarding, and test mode never verifies a live event.

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Next.js App Router: read text before anything else

Route handlers do not parse bodies unless you ask, so the raw text is one call away. Do not call request.json() anywhere in the handler, even for logging.

ts
// app/api/stripe/route.ts import Stripe from "stripe"; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!); export async function POST(request: Request) { const payload = await request.text(); const signature = request.headers.get("stripe-signature") ?? ""; let event: Stripe.Event; try { event = stripe.webhooks.constructEvent( payload, signature, process.env.STRIPE_WEBHOOK_SECRET! ); } catch (error) { return new Response(`Webhook Error: ${(error as Error).message}`, { status: 400 }); } switch (event.type) { case "checkout.session.completed": await fulfil(event.data.object); break; default: console.log(`Unhandled event ${event.type}`); } return Response.json({ received: true }); }

Response.json afterwards is safe: the body has been consumed.

Edge runtime needs constructEventAsync

On Vercel Edge, Cloudflare Workers, or Deno, crypto.createHmac does not exist, so the synchronous call throws SubtleCryptoProvider cannot be used in a synchronous context. The async variant is a drop-in with an await:

ts
export const runtime = "edge"; const event = await stripe.webhooks.constructEventAsync( payload, signature, process.env.STRIPE_WEBHOOK_SECRET!, undefined, Stripe.createSubtleCryptoProvider() );

Passing the provider explicitly avoids a warning where WebCrypto exists but Node crypto does not.

Fastify: register a scoped content type parser

Fastify parses application/json before your handler runs, so add a parser inside the plugin scope and keep the buffer as a string.

ts
await app.register(async (instance) => { instance.addContentTypeParser( "application/json", { parseAs: "string" }, (_request, body, done) => done(null, body) ); instance.post("/webhook", async (request, reply) => { const signature = request.headers["stripe-signature"]; try { const event = app.stripe.webhooks.constructEvent( request.body as string, signature as string, app.config.webhookSecret ); reply.send({ received: true, id: event.id }); } catch (error) { reply.code(400).send({ error: (error as Error).message }); } }); });

Registering it globally turns every JSON route into a string body and breaks the rest of the API.

Proxies, CDNs, and base64 payloads

Three infrastructure habits break the HMAC while leaving valid JSON: a Cloudflare Worker that does JSON.parse then JSON.stringify before forwarding, an API Gateway configured for binary media types that delivers base64 in event.body, and a middleware that adds a BOM or normalizes line endings. For Lambda, decode conditionally:

ts
const raw = event.isBase64Encoded ? Buffer.from(event.body ?? "", "base64").toString("binary") : event.body ?? "";

toString("binary") keeps byte values intact; utf8 re-encodes and breaks the signature for non-ASCII payloads, exactly what a customer name in Korean or Portuguese triggers.

Local forwarding with the CLI

stripe listen --forward-to localhost:3000/api/stripe prints a whsec_... for that session. Use it locally and never deploy it: it changes each restart, while the deployed endpoint uses the dashboard secret.

bash
stripe listen --forward-to localhost:3000/api/stripe stripe trigger checkout.session.completed

To test verification without a live event, sign a payload yourself with stripe.webhooks.generateTestHeaderString({ payload, secret }). If that header verifies, the secret and code path are correct and the remaining problem is transport.

Common Compilation/Runtime Mistakes & Version Gotchas

Verifying req.body after express.json(). The object has no bytes left, and JSON.stringify(req.body) fails when the original used different spacing. Mount a raw parser for the webhook path.

Silently returning 200 on failure. Catching the verification error and answering 200 tells Stripe the event was delivered, so it will not retry and the payment is fulfilled nowhere. Return 400 for signature failures and let Stripe retry 5xx.

Comparing secrets across modes. A test-mode secret cannot verify a live event, and the error text is identical; log the mode beside the endpoint id.

Raising tolerance to fix clock skew. The default five minutes is replay protection; tolerance: 3600 masks a broken NTP client. Fix the clock instead.

Not handling post-verification failures. An unhandled rejection after a successful check still means an unfulfilled order. Log event.id and treat the handler as at-least-once: Stripe retries, so make fulfilment idempotent with a unique constraint on the event id.

Version floor. constructEventAsync and Stripe.createSubtleCryptoProvider exist in recent stripe Node releases; pin the SDK, because the header format has been stable for years while helper exports move.

While debugging, paste the payload into the JSON formatter to confirm what arrived, and check the status code reference for the response to send back.

Official references: Resolve webhook signature verification errors and the webhooks overview.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.