← Back to blog

Stripe webhook signature verification failed? The raw body fix, and why you cannot skip the check

Your Stripe webhook worked on your laptop. In production it throws Webhook signature verification failed, and paid customers are not getting what they bought. The fix is almost always one of two things: your framework changed the request body before Stripe's library saw it, or your server is using the wrong signing secret.

This post covers both fixes with code for Next.js and Express. It also covers the tempting shortcut, which is to switch the check off so the error goes away. If you do that, anyone who can guess your webhook URL can tell your app that a payment happened. So the second half explains what the check does, what it does not do, and what to confirm before you launch.

Why does Stripe webhook signature verification fail?

Stripe webhook signature verification fails when one of three inputs is wrong: the request body, the Stripe-Signature header, or the endpoint secret. The body must be the exact bytes Stripe sent. The secret must belong to the endpoint that received the event. A parsed body or a mismatched secret causes nearly every failure.

The full error reads No signatures found matching the expected signature for payload. It sounds like Stripe forgot to sign the request. It did not. The message means your server computed a signature of its own and it did not match the one in the header. Stripe's troubleshooting guide puts it simply: at least one of the three values you passed to constructEvent is incorrect.

InputWhat goes wrongHow to check
Request bodyThe framework parsed the JSON, then your code turned it back into a stringLog typeof body and Buffer.isBuffer(body). It should be a string or a Buffer, never a plain parsed object
Endpoint secretCLI secret used in production, test secret used in live mode, or a stray spaceCompare the last four characters with the dashboard
Signature headerA proxy stripped the header, or the code reads the wrong nameLog it. It should start with t= and contain a v1= entry

Work through the table from the top. The body is the usual problem in new projects. The secret is the usual problem when the code worked yesterday and broke after a deploy.

How do you fix the raw body error in Next.js and Express?

To fix the raw body error, give constructEvent the request body exactly as it arrived. In the Next.js App Router, read it with await req.text() and not req.json(). In Express, put express.raw() on the webhook route and register it before express.json(). Never rebuild the body with JSON.stringify.

The reason is simple once you see it. Stripe signs the body as a string of bytes. When a framework parses that JSON into an object, the original spacing and key order are gone. Turning the object back into text produces different bytes, so the signature no longer matches, even though the data is the same.

In the Next.js App Router, the working version looks like this:

// app/api/webhooks/stripe/route.js
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY)

export async function POST(req) {
  const body = await req.text() // raw string, not req.json()
  const sig = req.headers.get('stripe-signature')

  let event
  try {
    event = stripe.webhooks.constructEvent(
      body, sig, process.env.STRIPE_WEBHOOK_SECRET
    )
  } catch (err) {
    return new Response('Invalid signature', { status: 400 })
  }

  // Only now is event safe to act on
  return new Response('ok')
}

In Express, order matters, because middleware runs in the order you register it. The webhook route needs the raw body, and every other route can keep the JSON parser:

// The webhook route comes first, with a raw body
app.post('/webhooks/stripe',
  express.raw({ type: 'application/json' }),
  (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('Invalid signature')
    }
    res.sendStatus(200)
  })

// The JSON parser for everything else comes after
app.use(express.json())

A few other setups have their own version of the same trap:

  • Next.js Pages Router: export a config that sets bodyParser: false for the route, then read the request as a buffer. That config does nothing in the App Router.
  • Cloudflare Workers and other edge runtimes: use await stripe.webhooks.constructEventAsync(...), because the crypto API there is asynchronous.
  • AWS API Gateway with Lambda: the gateway can reshape the body before your function sees it. Stripe's guide includes a mapping template that passes the raw body through.

Stripe keeps working webhook examples for Express, Koa, NestJS, Next.js and Deno in the stripe-node repository. If your framework is on that list and your code differs from the example, start there.

Why does the webhook work locally but fail in production?

A webhook that works locally but fails in production is usually using the wrong signing secret. The Stripe CLI prints its own whsec_ secret when you run stripe listen. Each dashboard endpoint has a different one, and test mode and live mode differ again. Production must use the secret of the live endpoint.

Stripe's guide calls the wrong secret the most common cause of this error. It is easy to see why. During development you copy the CLI secret into .env. At launch you copy the same file into your host's settings. The value starts with whsec_ and looks right, but it belongs to a listener on your laptop.

There can be four different secrets in play for one app:

  • The CLI secret from stripe listen, for local testing only.
  • The secret for your test mode (sandbox) endpoint.
  • The secret for your live mode endpoint.
  • One more for each extra endpoint you register, such as a preview deployment.

Open the endpoint in the Stripe dashboard, reveal its secret, and paste that exact value into the environment that serves that URL. Check for a trailing space or newline, which hosting dashboards add more often than you would expect. Then redeploy, since most hosts only load new variables on a fresh deploy.

Two related mix-ups are worth ruling out. The signing secret is not your API key: the API key starts with sk_ and the signing secret starts with whsec_. And both belong in server-only variables. A secret with a client prefix ends up in your JavaScript bundle, which is the mistake covered in why frontend env variables are not secret.

Do you need to verify Stripe webhook signatures?

Yes. You need to verify Stripe webhook signatures on any endpoint that changes something: marking an order paid, upgrading a plan, or sending a download link. Your webhook URL is public and takes requests from anyone. The signature is the only proof inside the request that Stripe sent it.

A webhook endpoint is unusual. Every other sensitive route in your app sits behind a login. This one cannot, because Stripe has no account on your site. It has to accept a POST from the open internet, and the event format is published in Stripe's API reference for anyone to copy.

Stripe's webhook documentation says to verify every event, and it warns that without the check an attacker can send fake events that fulfill orders or grant account access. It recommends two protections together: checking the signature, and only accepting requests from Stripe's published IP addresses. On serverless hosts you often cannot filter by IP address. That leaves the signature as the one protection you fully control.

A webhook handler without a signature check is a public "mark this order as paid" button. The only thing protecting it is that nobody has looked for it yet.

What happens if you skip webhook signature verification?

If you skip webhook signature verification, anyone who finds your endpoint can post a fake checkout.session.completed event with their own account ID in it. Your handler then treats it as a real payment. They get the paid plan, the credits or the download, and no money ever moves.

The attack takes no special skill. The attacker does not need your Stripe keys. They need three things:

  • Your webhook URL. Most apps use a predictable path such as /api/webhooks/stripe or /api/stripe/webhook.
  • The event shape. It is public, and a real example is one search away.
  • Their own user ID or email. They place it wherever your handler looks, usually client_reference_id, customer_email or metadata.

One curl command later, your database says they paid. Nothing shows up in Stripe, because Stripe was never involved. You might only notice weeks later, when your paid user count and your revenue do not agree.

The check is often missing in ways that are easy to overlook. These four patterns all leave the door open while the code still looks like it verifies:

  • The fallback. A catch block that logs the error and then parses the body anyway.
  • The conditional. Code that only verifies if (process.env.STRIPE_WEBHOOK_SECRET) is set. If the variable is missing in production, the check is skipped without a sound.
  • The dev bypass. A flag such as SKIP_WEBHOOK_VERIFY, added during testing and left on.
  • The zero tolerance. Stripe's docs warn that a tolerance value of 0 turns off the timestamp check.

AI coding tools produce the first three often, for the same reason they produce other shortcuts. You asked for the error to go away, and removing the check does that fastest. The app works and the demo runs. It is the same pattern described in the hidden security cost of vibe coding: the flaw sits in the part nobody tested.

How does the Stripe-Signature header work?

The Stripe-Signature header carries a timestamp (t) and one or more signatures (v1). Stripe makes each signature by running HMAC with SHA-256 over the timestamp, a dot and the raw body, keyed with your endpoint secret. Your server repeats that calculation and compares the results.

You do not need to write any of this yourself, since constructEvent does it. But knowing the parts makes the errors easier to read. A header looks like this:

Stripe-Signature: t=1798765432,v1=5257a869e7ec...,v0=6ffbb59b2300...

Each part has a job, as laid out in Stripe's manual verification steps:

  • t is when Stripe signed this delivery. Because it is part of the signed text, nobody can change it without breaking the signature.
  • v1 is the real signature. There can be more than one, for example while you are rolling a secret. One match is enough.
  • v0 is a fake signature that Stripe adds to sandbox events. It is never valid, and your code should ignore it.

The timestamp is there to stop replay attacks, where someone captures a real, signed request and sends it again later. Stripe's libraries reject any event whose timestamp is more than 5 minutes old by default. That is also why a server with a badly wrong clock can fail verification even when everything else is right.

Newer deliveries may also carry secret, destination and payload entries in the header. These are debugging hints, and they are not signed. The destination entry names the endpoint Stripe sent to, which helps you find the matching secret. Never use these entries to decide whether a request is real.

What does signature verification not protect you from?

Signature verification proves that an event came from Stripe and was not altered. It does not stop duplicate deliveries, events arriving out of order, or a handler that trusts the wrong field. A verified event can still grant access twice, or grant access for a payment that has not cleared yet.

Four more habits close those gaps, and each comes from Stripe's own guidance:

  • Expect duplicates. Stripe can deliver the same event more than once. Store each event ID you process and skip any ID you have already seen.
  • Do not rely on order. Stripe does not promise that events arrive in the order they happened. If you need the current state, fetch the object from the API.
  • Reply fast. Return a 2xx status before doing slow work. If your endpoint errors or times out, Stripe retries for up to three days in live mode, so a slow handler creates its own duplicates.
  • Check that payment cleared. For delayed payment methods, checkout.session.completed can arrive before the money does. Stripe's fulfillment guide covers checking the session's payment status before you deliver anything.

The signing secret itself needs the same care as any other key. If it has ever been committed to a repository, treat it as leaked, because deleting the line does not remove it from history. That trap is covered in how git history keeps leaking deleted keys. Stripe lets you roll the secret from the dashboard and keep the old one valid for up to 7 days, so you can switch over with no missed events.

A webhook checklist to run before launch

Run through this list once before you take real payments. It takes about ten minutes.

  1. Find every webhook route. Search your code for webhook. Each Stripe route should call constructEvent or constructEventAsync before it reads anything from the event.
  2. Read the catch block. A failed check must return a 400 and stop. It must not fall through to parsing the body.
  3. Make a missing secret fatal. If STRIPE_WEBHOOK_SECRET is empty, the handler should throw, not skip the check.
  4. Match the secret to the endpoint. The production variable holds the live endpoint's secret, not the CLI one.
  5. Send a forged request yourself. Post a made-up event to your deployed URL with curl and no signature header. You should get a 400 and no change in your database.
  6. Send a real one. Use the dashboard or stripe trigger checkout.session.completed and confirm the delivery shows as succeeded.
  7. Deliver it twice. Resend the same event from the dashboard and confirm the customer is not credited twice.

Step five is the one most people skip, and it is the only one that tests what an attacker would try. Payments are one item on a longer list. The rest is in the backend security checklist for solo developers.

Scanning for this before you ship

You can find a missing check by reading your own code, and the list above shows where to look. If you would like a second pair of eyes, the free IOnclad browser scanner runs a 167-rule subset in your browser, with no signup and no email wall. One of those rules flags an Express-style route (app.post, router.post or app.use) whose path puts stripe next to webhook, such as /stripe/webhook or /webhook/stripe, in a file that never calls constructEvent. Similar rules cover GitHub and Clerk webhook handlers. Your code stays in the tab.

A pattern rule like that is a prompt to go and look, not proof either way. It can miss a check that lives in another file, and it cannot tell whether your catch block falls through. It does not match Next.js route handlers, which have no app.post line to find. It also goes by the route path, so a path such as /webhooks/stripe or a plain /webhook is not matched. A clean result in those cases tells you nothing about the webhook, so run the checklist above either way. The IOnclad desktop app looks wider, with 26 scanners and 600+ checks across secrets, git history, dependencies, auth and runaway cloud costs, and it returns one Ship-It verdict with a file, line and suggested fix for each finding. No scanner can promise an app is secure. What it can do is point at the webhook route with no signature check before a stranger finds it.

This post is part of our app security guides for indie developers.

Free, in your browser
IOnclad browser scanner

Check your app for exposed keys and the issues that stop a launch. No signup, no email wall, and your code never leaves the tab.

→
Keep reading
IOnclad Backend Security Checklist for Solo Devs Before You Launch Read → IOnclad Frontend Env Variables Are Not Secret: VITE_, NEXT_PUBLIC_ Read → IOnclad Denial of Wallet: How One Bug Can Run Up a $10,000 Bill Read →
Reading us on Google?
Add The IOn Project as a preferred source

One click on Google’s preferences page, and our articles show up more often in your Top Stories, AI Overviews, and AI Mode.

→