Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Payments and webhooks

Stripe webhook: no signatures found matching the expected signature

ErrorWebhook signature verification failed. Err: No signatures found matching the expected signature for payload.

Short answer

Stripe signs the exact bytes it sends, using that endpoint's own secret. Verification fails when your code checks something else: a body already parsed by express.json() or req.json(), a whsec_ secret from the CLI, another endpoint or the other mode, or a body that a gateway re-encoded. Pass the raw body, the Stripe-Signature header and the matching secret, and keep the server clock synced.

  • Applies to stripe Node.js SDK 23, Express 5, Next.js 16 App Router, NestJS 11 and 12 on Express, Stripe CLI
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Add one temporary log line to the webhook route, before verification. It answers the questions that separate the causes: did the body arrive as raw bytes, is it the body Stripe signed, is the secret the one Stripe used, and how old is the signature. Some deliveries carry optional, unsigned debug entries in the Stripe-Signature header for exactly this: payload (the end of the SHA-256 digest of the signed body) and secret (a masked copy of the newest active secret). Use them to diagnose, never to verify.

    import crypto from 'node:crypto'
    
    const header = String(req.headers['stripe-signature'] ?? '')
    const parts = Object.fromEntries(header.split(',').map((kv) => kv.split('=')))
    const raw = Buffer.isBuffer(req.body) || typeof req.body === 'string' ? req.body : null
    console.log({
      bodyIsRaw: raw !== null,
      bodyMatchesStripe: raw && parts.payload
        ? crypto.createHash('sha256').update(raw).digest('hex').endsWith(parts.payload)
        : 'unknown',
      secretTailHere: process.env.STRIPE_WEBHOOK_SECRET?.slice(-4),
      secretTailStripe: parts.secret?.slice(-4),
      signedSecondsAgo: Math.round(Date.now() / 1000) - Number(parts.t),
    })
  2. 2Match what you see, then jump to its fix

    1. 1bodyIsRaw is false in the log, or the SDK says the payload must be a string or a Buffer and that it received a parsed JavaScript object.express.json() or the framework's body parser ran firstFix
    2. 2The same logic worked under Express but fails as a Next.js route; the handler calls req.json(), or hands JSON.stringify(body) to constructEvent.A Next.js route handler reads the body as JSONFix
    3. 3bodyIsRaw and bodyMatchesStripe are both true, verification still fails, and secretTailHere differs from secretTailStripe.The secret belongs to another endpoint, the CLI or the other modeFix
    4. 4bodyIsRaw is true but bodyMatchesStripe is false: the bytes you verify are not the bytes Stripe signed.Something between Stripe and your code changes the bodyFix
    5. 5Timestamp outside the tolerance zone; signedSecondsAgo in the log is above 300.The server clock is off, or verification happens long after deliveryFix

What does the error look like?

  • Webhook signature verification failed. Err: No signatures found matching the expected signature for payload.
  • No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
  • Webhook payload must be provided as a string or a Buffer
  • Timestamp outside the tolerance zone

Cause 1 of 5

express.json() or the framework's body parser ran first

1Check

Express runs middleware in the order it is registered. A global app.use(express.json()) above the webhook route turns the body into an object, and serialising it again never reproduces Stripe's bytes: spacing, key order and line endings change. NestJS on Express parses JSON for every route unless raw bodies are switched on.

grep -rnE "express\.json|bodyParser\.json|app\.use\(json|rawBody" src 2>/dev/null

2Fix

Give the webhook route its own raw parser and register it before the JSON middleware. In NestJS, create the app with rawBody: true and verify against req.rawBody, which is a Buffer, while other routes keep their parsed body.

// Express 5
import express from 'express'
import { Stripe } from 'stripe'

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)
const app = express()

app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  let event
  try {
    event = stripe.webhooks.constructEvent(
      req.body, req.headers['stripe-signature'], process.env.STRIPE_WEBHOOK_SECRET)
  } catch (err) {
    return res.status(400).send(`Webhook Error: ${err.message}`)
  }
  await queue.add('stripe-event', { id: event.id, type: event.type })   // slow work later
  res.json({ received: true })
})

app.use(express.json())   // every other route, registered after the webhook

// NestJS: main.ts
const app = await NestFactory.create<NestExpressApplication>(AppModule, { rawBody: true })

// NestJS: controller method
@Post('webhook')
@HttpCode(200)
async handle(@Req() req: RawBodyRequest<Request>, @Headers('stripe-signature') sig: string) {
  let event: Stripe.Event
  try {
    event = this.stripe.webhooks.constructEvent(req.rawBody!, sig, this.webhookSecret)
  } catch (err) {
    throw new BadRequestException(`Webhook Error: ${(err as Error).message}`)
  }
  await this.events.enqueue(event)
  return { received: true }
}

3Verify

Forward events from the Stripe CLI to the local route and trigger one; the listener prints a 200 for the delivery.

stripe listen --events payment_intent.succeeded --forward-to localhost:4242/webhook
# second terminal
stripe trigger payment_intent.succeeded
Did this fix it?

Cause 2 of 5

A Next.js route handler reads the body as JSON

1Check

A request body can be read only once. Once req.json() has run, the original text is gone, and stringifying the object again gives different bytes. In the Pages Router, the built-in body parser does the same thing unless it is switched off for that route.

grep -rnE "req(uest)?\.json\(\)|JSON\.stringify\(.*body|constructEvent" app pages src 2>/dev/null

2Fix

In the App Router, read the body with req.text() and pass that string straight to constructEvent. In the Pages Router, turn the body parser off for the webhook route and pass the raw buffer.

// app/api/webhooks/stripe/route.ts (App Router)
import { Stripe } from 'stripe'

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)

export async function POST(req: Request) {
  const body = await req.text()                  // raw text; never call req.json() first
  const signature = req.headers.get('stripe-signature') ?? ''
  let event: Stripe.Event
  try {
    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!)
  } catch (err) {
    return new Response(`Webhook Error: ${(err as Error).message}`, { status: 400 })
  }
  await enqueue(event)
  return Response.json({ received: true })
}

// pages/api/webhooks/stripe.ts (Pages Router)
export const config = { api: { bodyParser: false } }

async function readRaw(req: NextApiRequest): Promise<Buffer> {
  const chunks: Buffer[] = []
  for await (const chunk of req) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
  return Buffer.concat(chunks)
}

3Verify

Forward a test event to the Next.js route: the CLI shows a 200, and your log shows the event id.

stripe listen --events checkout.session.completed --forward-to localhost:3000/api/webhooks/stripe
# second terminal
stripe trigger checkout.session.completed
Did this fix it?

Cause 3 of 5

The secret belongs to another endpoint, the CLI or the other mode

1Check

Each endpoint has its own whsec_ secret, and the same URL registered in a sandbox and in live mode has a different secret in each. The secret printed by stripe listen belongs to the CLI forwarder, not to any Dashboard endpoint. Also look for quotes or a trailing newline that came along when the value was pasted.

stripe listen --print-secret                                                # the CLI forwarder's secret
node -e "console.log(JSON.stringify(process.env.STRIPE_WEBHOOK_SECRET))"    # shows quotes or \n

2Fix

Use the CLI secret only while the CLI forwards events to you. Each deployed environment needs the secret of its own endpoint, in the matching mode, revealed in Workbench under Webhooks. When you roll a secret, Stripe can keep the old one valid for up to 7 days and signs with both, so deploy the new value inside that window.

# .env.local (development, while `stripe listen` runs)
STRIPE_WEBHOOK_SECRET=whsec_value_printed_by_stripe_listen

# production secret store: the live endpoint's own secret, no quotes, no newline
STRIPE_WEBHOOK_SECRET=whsec_value_revealed_for_the_live_endpoint

3Verify

Resend a recent event to the deployed endpoint and check its delivery in Workbench shows 200.

stripe events resend evt_123 --webhook-endpoint=we_123
Did this fix it?

Cause 4 of 5

Something between Stripe and your code changes the body

1Check

Walk every hop: an API gateway mapping, a serverless adapter that passes a parsed event, a logging or sanitising middleware that rewrites JSON, a charset conversion. Log the digest at each layer you control; the first layer where it stops matching the payload entry is the one that alters the body.

const tail = (buf) => crypto.createHash('sha256').update(buf).digest('hex').slice(-8)
console.log('edge', tail(rawAtEntry), 'handler', tail(rawInHandler), 'stripe', parts.payload)

2Fix

Verify on the raw bytes at the first place your code receives them, before anything decodes or rewrites JSON, and pass the verified event onward. If a platform cannot hand you the raw body, use its raw-body option or move the webhook to a route that can.

// AWS Lambda behind an API Gateway proxy integration
export const handler = async (event) => {
  const raw = event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body
  const sig = event.headers['stripe-signature'] ?? event.headers['Stripe-Signature']
  const verified = stripe.webhooks.constructEvent(raw, sig, process.env.STRIPE_WEBHOOK_SECRET)
  await enqueue(verified)
  return { statusCode: 200, body: '{"received":true}' }
}

3Verify

The diagnostic log shows bodyMatchesStripe: true, and the delivery succeeds.

grep -c 'bodyMatchesStripe: false' app.log   # expect 0 after the fix
Did this fix it?

Cause 5 of 5

The server clock is off, or verification happens long after delivery

1Check

The signed payload includes a timestamp, and the official libraries reject it when it is more than 5 minutes away from the server's clock. A drifting clock trips this, and so does storing the request to verify later from a queue. Every retry from Stripe carries a fresh timestamp and signature.

timedatectl status | grep -iE 'synchronized|NTP service'

2Fix

Turn on time synchronisation and verify the moment the request arrives; queue the verified event, not the raw request. Keep the default tolerance; a tolerance of 0 switches the age check off entirely.

sudo timedatectl set-ntp true

// verify on arrival (default tolerance 300 seconds), then queue
const event = stripe.webhooks.constructEvent(raw, sig, secret)
await queue.add('stripe-event', { id: event.id, type: event.type })

3Verify

timedatectl reports System clock synchronized: yes, and signedSecondsAgo stays within a few seconds.

timedatectl status | grep -i synchronized
Did this fix it?

How do I stop it coming back?

  • Mount the webhook route first with its own raw parser, and keep a test that signs a sample payload with stripe.webhooks.generateTestHeaderString and posts it to the route.
  • Store one secret per endpoint and per mode, named so the two cannot be swapped.
  • Answer 2xx quickly and process in the background, deduplicating by event id because Stripe can deliver an event more than once.
  • Keep time synchronisation on for every server that verifies webhooks.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

The browser blocks your API response: no Access-Control-Allow-Origin header

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/orders. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

The browser received the response but refused to hand it to your script, because it did not carry an Access-Control-Allow-Origin header naming the page's origin.

4 causes, each with a fix

Payments

Stripe Elements shows console warnings or errors in a Next.js checkout

Could not find Elements context; You need to wrap the part of your app that calls useElements() in an <Elements> provider.

Most React Stripe.js warnings come from four mistakes: calling loadStripe inside a component, using useStripe or useElements outside the Elements provider, using the objects before they have loaded, and a Content Security Policy that blocks js.stripe.com.

4 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.