Stripe webhook not working in production: payment succeeds, nothing unlocks
Your app takes money. Stripe shows the payment as Succeeded, the customer gets a receipt, and then nothing happens in your app: the account stays on the free plan, the order never appears, the credits never arrive. In test mode it all worked. In production the webhook fails, and Stripe's dashboard shows a row of red 400, 401 or timed-out deliveries.
This is one of the most common breaks in apps built with Lovable, Bolt, Cursor, v0 or Replit, because the AI wires up Checkout quickly but the webhook depends on settings that live outside the code: the right signing secret for the right mode, an endpoint Stripe can actually reach, and a handler that reads the request body exactly as Stripe sent it. This guide walks through each cause in the order you should check them. If the problem is that environment variables are missing in general, read Environment variables missing in production first.
Step 0: read the delivery log before touching code
Open your webhook endpoint in the Stripe Dashboard (under Developers, shown as Workbench in newer accounts) and look at its event deliveries. Each failed attempt shows the HTTP status your server returned and the response body. That status tells you which section of this guide you need:
| What Stripe shows | What it usually means | Go to |
|---|---|---|
| No delivery attempts at all | The endpoint isn't registered in this mode (test vs live), or the event type isn't selected on it. | 1 and 6 |
400 with "No signatures found matching the expected signature for payload" | Wrong signing secret, or the body was changed before verification. | 2 and 3 |
401 or 403 | Something in front of your handler wants a logged-in user: Supabase JWT checks, Vercel Deployment Protection, or your own auth middleware. | 4 |
301, 302, 307, 308 | The URL redirects (www vs non-www, http vs https, a trailing slash, or a login redirect). Stripe treats redirects as failures. | 5 |
404 | Wrong path, or the function was never deployed to production. | 5 |
500 | The handler crashed after verification: a missing env var, a database error, or a blocked write. | 6 |
| Timed out | The handler does slow work before answering. | 7 |
200, but the app still doesn't unlock | The webhook works; the logic after it doesn't. | 6 |
Also open your host's logs for the same minute (Vercel Logs, Supabase Edge Function logs, Replit Deployment logs). The status in Stripe plus the error line in your logs is usually enough to pinpoint the cause.
1. Test mode and live mode are two separate setups
Stripe keeps test and live data apart, and that includes webhooks. An endpoint you created while testing does not receive live events, and each endpoint has its own signing secret. When you switch to live payments you need, all at once:
- A webhook endpoint created in live mode that points at your production URL.
- That endpoint's own
whsec_...signing secret in your production environment variables. - The live secret key (
sk_live_...) on the server and the live publishable key (pk_live_...) in the browser. - Live price IDs. Prices created in test mode don't exist in live mode, so a hard-coded
price_...from testing makes Checkout fail.
Mixing them causes confusing results. A common one: you click "send test event" or replay a test event against an endpoint that verifies with the live secret, and the signature check fails even though the code is fine. The event's mode and the secret's mode must match.
2. The signing secret is wrong, stale, or not loaded
Stripe's own docs name the wrong endpoint secret as the most common cause of signature errors. Check these in order:
- It must be the webhook signing secret, which starts with
whsec_. Not the secret key (sk_), not the publishable key (pk_). - It must belong to this exact endpoint. The secret printed by
stripe listenon your laptop is different from the secret of the endpoint in the Dashboard. Copying the CLI secret into production is a classic mistake. - It must be loaded at runtime. Log whether the variable exists (never log the value itself). On Vercel, a changed variable only applies to new deployments, so redeploy. On Supabase, set it as a function secret, for example
supabase secrets set STRIPE_WEBHOOK_SECRET=whsec_.... - Watch for copy-paste damage: a trailing space, a newline, or quotes pasted into the value field.
- An empty secret now fails loudly. Since
stripefor Node 23.0.1 (October 22, 2026), a signing secret made only of spaces or line breaks is rejected instead of being used, so you get an error about the secret rather than a confusing signature mismatch. If that starts after you upgrade, the variable is blank in that environment: set the realwhsec_value and redeploy.
3. The request body was changed before verification
Stripe signs the exact bytes it sends. If your framework parses the body into JSON first and you pass the re-serialized object to the verifier, the signature no longer matches. AI tools get this wrong often, and sometimes rewrite a correct handler into a broken one while "fixing" something nearby. Read the raw body, verify, and only then parse.
Next.js App Router (Cursor, v0)
// app/api/webhooks/stripe/route.ts
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 body, not req.json()
const sig = req.headers.get("stripe-signature");
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, sig!, process.env.STRIPE_WEBHOOK_SECRET!);
} catch (err) {
return new Response("Bad signature", { status: 400 });
}
// handle event.type here (see section 6), then:
return new Response("ok", { status: 200 });
}
Keep this route on the Node.js runtime unless you know your Stripe setup works on the edge.
Next.js Pages Router
Turn off the built-in body parser for the webhook route with export const config = { api: { bodyParser: false } }, read the raw request stream into a buffer, and pass that buffer to constructEvent.
Express (Replit, Bolt exports with a Node server)
// The webhook route needs the raw body, so register it BEFORE express.json()
app.post("/api/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("Bad signature");
}
res.sendStatus(200);
});
app.use(express.json()); // other routes
Supabase Edge Function (Lovable, Bolt)
Lovable and Bolt apps usually handle Stripe in a Supabase Edge Function. Edge Functions run on Deno, which needs the async verifier and a Web Crypto provider:
import Stripe from "npm:stripe";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY")!);
const cryptoProvider = Stripe.createSubtleCryptoProvider();
Deno.serve(async (req) => {
const body = await req.text();
const sig = req.headers.get("Stripe-Signature")!;
try {
const event = await stripe.webhooks.constructEventAsync(
body, sig, Deno.env.get("STRIPE_WEBHOOK_SECRET")!, undefined, cryptoProvider
);
// handle event.type here
return new Response("ok", { status: 200 });
} catch (err) {
return new Response("Bad signature", { status: 400 });
}
});
If the code calls the synchronous constructEvent in an Edge Function, it fails even with the right secret. That's a different error from a bad signature, so read the function log carefully.
4. The endpoint demands a logged-in user
Stripe is the caller here, not your customer, so it has no session cookie and no user token. Anything that requires one returns 401 or 403 before your code runs:
- Supabase Edge Functions check for a valid JWT by default. Turn that off for the webhook function only, with
supabase functions deploy stripe-webhook --no-verify-jwtorverify_jwt = falseunder[functions.stripe-webhook]insupabase/config.toml. The Stripe signature check is what protects this function, so it must stay. - Vercel Deployment Protection puts a login wall in front of preview deployments. Point the live webhook at your production domain, not a
...-git-branch-....vercel.apppreview URL. - Your own middleware (Clerk, NextAuth, Supabase auth helpers, a custom
middleware.ts) may protect every/apiroute, or redirect anonymous requests to/login. Exclude the webhook path from the auth matcher.
5. The URL redirects or doesn't exist
Stripe doesn't follow redirects: it records any 3xx response as a failed delivery. Paste the exact endpoint URL into a terminal with curl -i -X POST https://yourdomain.com/api/webhooks/stripe and look at the status. You want a 400 from your own code (no signature was sent), not a redirect or a 404. Typical fixes:
- Use the final domain your host serves:
https://, andwwwor not, whichever doesn't redirect. - Match the trailing slash exactly. With
trailingSlash: truein Next.js, a URL without the slash can get a308redirect. - Check the path in the code against the URL in Stripe. AI tools rename routes (
/api/stripe/webhookvs/api/webhooks/stripe) more often than you'd expect. - For Supabase, confirm the function is actually deployed to the production project:
https://<project-ref>.supabase.co/functions/v1/<function-name>. - On a static host (a Vite single-page app on Netlify or GitHub Pages) there is no server at all, so the webhook has to live in a serverless or edge function.
6. The webhook returns 200, but the app never unlocks
Now Stripe is happy and the problem is your own logic. The usual suspects:
- The success page is doing the unlocking. Many generated apps upgrade the user when the browser lands on
/success. That breaks when the customer closes the tab, and anyone can open that URL. Let the webhook grant access, and let the success page just show the status. - The event type isn't subscribed. The endpoint only receives the events you selected. For one-time payments you usually need
checkout.session.completed. For subscriptions, alsocustomer.subscription.updated,customer.subscription.deleted,invoice.paidandinvoice.payment_failed, or renewals and cancellations never reach your database. - The webhook can't tell which user paid. Matching by email fails when people pay with a different address. Pass your user ID when you create the Checkout Session (
client_reference_idormetadata) and read it back in the webhook. - Row Level Security blocks the write. The webhook has no user session, so a Supabase client built with the anon key gets an empty result or a
42501error. Use a server-side client with theservice_rolekey inside the webhook only, never in browser code. See Supabase auth: redirect URLs and RLS for how those policies work. - It's writing to the wrong database. The production function still points at a development Supabase project or a local SQLite file, so the row lands somewhere your live app never reads.
7. Timeouts, retries and duplicate events
Stripe expects a quick 2xx and recommends answering before any slow work. If your handler sends emails, calls an AI model or generates files before it answers, the delivery can time out and Stripe tries again. In live mode Stripe retries failed deliveries for up to three days with exponential backoff; test deliveries are retried three times over a few hours.
Two consequences matter for your code:
- The same event can arrive more than once. Store each
event.idyou process (a table with a unique constraint works) and skip ones you've already handled, so a retry never grants credits twice. - Events don't arrive in order. Stripe doesn't guarantee ordering, so
invoice.paidcan show up beforecustomer.subscription.created. Write handlers that can fetch the latest object from the Stripe API instead of assuming the earlier event already ran.
Test it properly before real customers do
- Locally, run
stripe listen --forward-to localhost:3000/api/webhooks/stripe, use thewhsec_it prints in your local env only, and fire events withstripe trigger checkout.session.completed. - On the deployed app, send a test event from the endpoint page in the Dashboard and confirm a
200plus the expected row in your database. - Do one real low-value live purchase yourself, check that the account unlocks, then refund it from the Dashboard.
- Once the fix is live, resend the failed events from the delivery log (or with
stripe events resend) so customers who already paid get what they bought.
What not to do
- Don't remove signature verification to "make it work". Without it, anyone who finds the URL can post a fake
checkout.session.completedand unlock your product for free. - Don't trust IDs from the success URL without checking them against Stripe on the server.
- Don't put
sk_live_orwhsec_in browser code or behind aVITE_orNEXT_PUBLIC_prefix. If one leaked, roll it in the Stripe Dashboard and update your environment.
How to prompt your AI tool for this fix
My Stripe webhook fails in production with [status from the Stripe delivery log] and
this log line: [paste error]. Do not change pricing, checkout or UI code.
Check only the webhook handler: it must read the raw body, verify the
Stripe-Signature with STRIPE_WEBHOOK_SECRET, not require a user session,
answer 200 quickly, skip event IDs it already processed, and update the
database with a server-side client. Show me the exact lines you change.
Scoping the prompt like this keeps the tool from rewriting checkout while it hunts for the bug. If it still loops, here's how to break the AI fix loop.
A go-live checklist for Stripe webhooks
- Live-mode endpoint exists and points at the production URL, with no redirect.
- Its
whsec_secret is in production env vars, and the app was redeployed after adding it. - Live secret key, publishable key and price IDs are in place.
- Handler reads the raw body and verifies the signature.
- Webhook path is excluded from auth, JWT checks and deployment protection.
- All needed event types are selected.
- The user is identified by
client_reference_idor metadata, not by email. - Database writes use a server-side client and go to the production database.
- Duplicates are skipped by event ID, and the handler answers within a few seconds.
FAQ
Why does my Stripe webhook work in test mode but not in production?
Test and live mode are separate. A webhook endpoint created in test mode doesn't receive live events, and every endpoint has its own whsec_ signing secret. Create a live-mode endpoint for your production URL, put its signing secret in your production environment variables, redeploy, and use live keys and live price IDs.
What does "No signatures found matching the expected signature for payload" mean?
The signature check failed. Either the signing secret is wrong (a CLI secret, a test secret, a secret from another endpoint, or a value with extra spaces), or the request body was parsed or changed before verification. Pass the raw body string or buffer, the Stripe-Signature header and the endpoint's whsec_ secret to the verifier.
Why does my Supabase Edge Function return 401 to Stripe?
Supabase Edge Functions require a valid user JWT by default, and Stripe doesn't send one. Deploy the webhook function with --no-verify-jwt or set verify_jwt = false for it in supabase/config.toml, and keep the Stripe signature check in the code as the protection.
Should the success page unlock the paid features?
No. Customers can close the tab before it loads, and anyone can open the URL. Let the verified webhook update the database, identify the user with client_reference_id or metadata, and have the success page only show the current status.
Why did a customer get charged once but credited twice?
Stripe can deliver the same event more than once, for example after a timeout. Store each processed event ID with a unique constraint and skip duplicates, and answer with a 2xx quickly before doing slow work.