Stripe Webhooks in Production: Signatures, Retries and Idempotency
On this page
Verify Stripe webhook signatures, handle retries and unordered events, and keep handlers idempotent. Includes Node and Supabase Edge Function code.
A production Stripe webhook endpoint does four jobs: it verifies the Stripe-Signature header against the raw request body, returns a 2xx response before it does real work, records every event ID so a duplicate changes nothing, and fetches the current object from Stripe instead of trusting the order of events. This guide covers those four jobs for founders and small teams who bill customers through Stripe, with Node and Supabase Edge Function code. It extends our general guide to webhooks for startups with Stripe's own behaviour, checked against Stripe's documentation on 17 November 2026.
Key takeaways
- Stripe signs each request with an HMAC SHA-256 signature over the timestamp and the raw body, so a parsed body fails verification.
- Live mode retries a failed delivery for up to three days. A sandbox retries three times over a few hours.
- Stripe does not guarantee event order, so treat each event as a prompt to fetch the current object.
- Store each event ID before you process the event, and send an idempotency key with the API calls your handler makes.
What does a Stripe webhook request contain?
Stripe sends an HTTPS POST with a JSON event in the body and a Stripe-Signature header. You register the URL as an event destination in Workbench or through the API, and Stripe allows up to 16 event destinations. Each destination has its own signing secret, which starts with whsec_. The same URL has a different secret in test mode and in live mode.
The header carries comma-separated entries:
tis the Unix timestamp of the moment Stripe signed the event.v1is the HMAC SHA-256 signature of the timestamp, a period and the unmodified body. The header holds more than onev1value while you roll a secret.v0appears on sandbox events, and your verification code must ignore it.secret,destinationandpayloadare debugging entries. An attacker can forge them, so do not use them to authenticate a request.
Which event format should you use, snapshot or thin?
Stripe documents two payload formats. A snapshot event carries the object as it looked when the event fired. A thin event carries the event type and a reference to the related object, and your code fetches the object from the API. As of 17 November 2026 the Stripe webhooks guide recommends thin events for new integrations. It keeps snapshot events for third-party tools that need the full event object and for code that needs previous_attributes without another API call.
| Snapshot event | Thin event | |
|---|---|---|
| Payload | The object as it was when the event fired | The event id, type and a related_object reference |
| Event names | invoice.paid |
A v1. prefix, such as v1.payment_intent.succeeded |
| Node verification | stripe.webhooks.constructEvent() |
stripe.parseEventNotification() |
| Current data | Read data.object or call the API |
fetchRelatedObject() |
The subscription guide lists its events in snapshot form, such as invoice.paid and customer.subscription.updated, and most existing Stripe code uses snapshot handlers. This guide uses snapshot events for that reason. Thin events build the fetch-the-current-object habit into the handler, and the ordering section below recommends the same habit for snapshot events.
How do you verify a Stripe webhook signature?
Pass the raw request body, the Stripe-Signature header and the endpoint secret to Stripe's library. The README of the Node library shows the call:
const event = stripeClient.webhooks.constructEvent(
webhookRawBody,
webhookStripeSignatureHeader,
webhookSecret
);
The README warns that the function needs the raw request body as Stripe sent it and does not work on a parsed JSON body. An Express handler that follows the pattern in Stripe's Node quickstart looks like this:
const express = require('express');
const Stripe = require('stripe');
const stripe = new Stripe(process.env.STRIPE_API_KEY);
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;
const app = express();
// This route needs the raw body, so register it before express.json().
app.post('/webhook', express.raw({ type: 'application/json' }), async (request, response) => {
const signature = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, signature, endpointSecret);
} catch (err) {
console.log('Webhook signature verification failed.', err.message);
return response.sendStatus(400);
}
try {
// Store the event and return. A worker does the slow work later.
await saveEvent(event);
} catch (err) {
console.log('Could not store the event.', err.message);
return response.sendStatus(500);
}
response.sendStatus(200);
});
app.use(express.json()); // every other route
app.listen(4242, () => console.log('Running on port 4242'));
Stripe lists three common causes of a verification error: the signing secret of a different event destination, a parsed copy of the body, and the wrong request header. A JSON parser that runs before your route causes the second one, so check your middleware order first.
Stripe's libraries apply a default tolerance of 5 minutes between the signed timestamp and the current time, which blocks replay of a captured request. A tolerance of 0 disables the recency check. Keep the server clock on NTP. Stripe creates a new timestamp and signature for each delivery attempt, so a retry passes the tolerance check when the first attempt happened hours earlier.
Stripe recommends signature verification together with an allowlist of its published IP addresses. Rails, Django and similar frameworks check for a CSRF token on POST requests, so exempt the webhook route.
When you roll a secret in Workbench, you can expire the old secret at once or keep it active for up to 7 days. During that window Stripe sends one signature per active secret, and your code accepts the request when at least one v1 value matches.
How do Stripe webhook retries work?
In live mode Stripe retries a failed delivery for up to three days with exponential backoff. In a sandbox it retries three times over a few hours. The Event deliveries tab for an endpoint in Workbench shows the delivery status and HTTP status code of each attempt, plus the time of the next retry.
| What your endpoint does | How Stripe treats it | Fix |
|---|---|---|
| Redirects with a 3xx status | Failure | Register the URL the redirect resolves to |
| Returns 400, 401, 403, 404 or 405 | Failure | Make the endpoint public and accept POST |
| Returns 500 or another 5xx status | Failure | Read your application logs |
| Takes too long to respond | Timed out | Return 2xx first and defer the work |
You can replay an event by hand. The Dashboard has a Resend button that works for up to 15 days after the event. The Stripe CLI resends for up to 30 days:
stripe events resend --webhook-endpoint=
A manual resend does not cancel the automatic retries when it returns a 2xx.
Return the 2xx before the slow work. Stripe's best-practice section calls for an asynchronous queue and warns that a spike, such as every subscription renewing at the start of the month, can overwhelm endpoint hosts that process events inline. Our guide to background jobs and task queues covers the queue options.
Why do Stripe events arrive out of order?
Stripe does not guarantee that events arrive in the order it generates them. Creating a subscription can produce customer.subscription.created, invoice.created, invoice.paid and charge.created in any order. Snapshot events record created in whole seconds, so two events can share a timestamp, and Stripe advises against using created to order events or to detect duplicates.
Fetch the object instead. When invoice.paid arrives before the subscription event, retrieve the invoice, charge and subscription from the API and work from their current state. The subscription guide applies the same rule to access: after invoice.paid, retrieve the subscription and confirm that its status is active before you extend access. A paid invoice does not guarantee that the subscription moves to active.
How do you make a Stripe webhook handler idempotent?
Stripe can deliver the same event more than once, and its guide describes two cases. In the first, one event arrives twice, so you log the IDs of processed events and skip repeats. In the second, Stripe generates two separate Event objects for the same change, and you spot them by the ID of data.object together with event.type.
Store the event before you process it. This table keeps the raw payload for replay, and the primary key blocks a repeated event ID:
create table stripe_events (
id text primary key,
type text not null,
object_id text,
payload jsonb not null,
received_at timestamptz not null default now(),
processed_at timestamptz
);
The saveEvent function in the handler above is one statement:
async function saveEvent(event) {
await db.query(
`insert into stripe_events (id, type, object_id, payload)
values ($1, $2, $3, $4)
on conflict (id) do nothing`,
[event.id, event.type, event.data.object.id, event]
);
}
A repeated event hits on conflict, inserts nothing and returns 200, which tells Stripe to stop retrying. A worker reads rows where processed_at is null, handles each event and sets processed_at. A crash in the middle of a handler leaves the row unprocessed, so the next pass finishes it. Write each action so that a second run produces the same state: set the plan from the fetched subscription instead of adding days to a counter.
Webhook deduplication protects the requests Stripe sends to you, and idempotency keys protect the requests your worker sends to Stripe.
curl https://api.stripe.com/v1/customers \
-u sk_test_...: \
-H "Idempotency-Key: KG5LxwFBepaKHyUD" \
-d description="My First Test Customer (created for API docs at https://docs.stripe.com/api)"
For API v1, all POST requests accept idempotency keys, and GET and DELETE requests ignore them. Stripe saves the status code and body of the first request made with a key and returns that saved response on a retry, including a 500 error. A key reused with different parameters returns an error. Stripe can remove keys that are at least 24 hours old, so a replay a week later creates a new request, and the stored event row protects you in that case. Build each key from the event ID so a retried event sends the same key. The Stripe documentation on idempotent requests lists the rules.
Which subscription events should your endpoint handle?
Subscribe to the events your integration needs and skip the rest. Stripe advises against listening to all events because the extra traffic strains your server. The subscription webhooks guide suggests these actions:
| Event | What to do |
|---|---|
invoice.paid |
Retrieve the subscription, confirm the status is active and extend access |
invoice.payment_failed |
Notify the customer and inspect the PaymentIntent status |
invoice.payment_action_required |
Ask the customer to complete authentication |
customer.subscription.updated |
Sync the plan and status after a renewal, a plan change or a coupon |
customer.subscription.deleted |
Revoke access when the subscription ends |
customer.subscription.trial_will_end |
Check for a payment method, because the trial ends in 3 days |
invoice.finalization_failed |
Read last_finalization_error on the invoice |
charge.refunded, charge.dispute.created and radar.early_fraud_warning.created |
Decide what happens to the customer's access |
The same guide sets the status rules. Notify the customer when a subscription becomes past_due, and revoke access when it becomes canceled or unpaid. For the billing model behind these events, see our guide to adding payments and subscription billing to a SaaS MVP.
One event deserves extra care. If Stripe receives no successful response to invoice.created, it delays the finalisation of invoices with automatic collection for up to 72 hours. After a successful response, Stripe waits an hour before it attempts payment. The delay applies to every endpoint on your account, so a failing endpoint from a connected platform or a third-party service can hold up your invoices as well. Stripe emails you when a webhook keeps failing.
How do you run a Stripe webhook on Supabase Edge Functions?
Teams that build on Supabase, including apps generated with Lovable, can host the endpoint in an Edge Function. Deno needs the asynchronous verification call, constructEventAsync, together with a Web Crypto provider. Supabase's example in its GitHub repository, read on 17 November 2026 and trimmed here, shows the shape:
import Stripe from 'npm:stripe@^22'
import { withSupabase } from 'npm:@supabase/server@^1'
const stripe = new Stripe(Deno.env.get('STRIPE_API_KEY') as string)
// This is needed in order to use the Web Crypto API in Deno.
const cryptoProvider = Stripe.createSubtleCryptoProvider()
// Stripe verifies the request via its signature, so deploy with verify_jwt = false.
export default {
fetch: withSupabase({ auth: 'none' }, async (req) => {
const signature = req.headers.get('Stripe-Signature')
// First step is to verify the event. The .text() method must be used as the
// verification relies on the raw request body rather than the parsed JSON.
const body = await req.text()
let receivedEvent
try {
receivedEvent = await stripe.webhooks.constructEventAsync(
body,
signature!,
Deno.env.get('STRIPE_WEBHOOK_SIGNING_SECRET')!,
undefined,
cryptoProvider
)
} catch (err) {
return new Response(err.message, { status: 400 })
}
console.log(`Event received: ${receivedEvent.id}`)
return Response.json({ ok: true })
}),
}
The comment in the example says Stripe verifies the request through its signature, so the function deploys with verify_jwt = false. That makes the signature check the gate for the endpoint, so store the signing secret as a secret and use a separate endpoint and secret for live mode. Our guide to Supabase Edge Functions and database functions explains when an Edge Function is the right host for this code.
How do you test a Stripe webhook before launch?
The Stripe CLI forwards sandbox events to your local server. Stripe's guide gives these commands:
stripe login
stripe listen --forward-to localhost:4242/webhook
stripe trigger payment_intent.succeeded
The stripe listen command prints a signing secret. Copy it into STRIPE_WEBHOOK_SECRET and restart the server. Run this drill before you go live:
- Send a POST with a bad signature and expect a 400 response.
- Resend one event with the CLI and expect a single row in
stripe_events. - Stop the worker in the middle of an event and expect the next pass to finish it.
- Return a 500 from a sandbox endpoint and watch the Event deliveries tab show the retries over a few hours.
Frequently asked questions
How long does Stripe retry a failed webhook?
In live mode Stripe retries for up to three days with exponential backoff. In a sandbox it retries three times over a few hours. The Event deliveries tab in Workbench shows when the next retry is due.
Can I replay an event that failed?
Yes. Click Resend on the event in the Dashboard within 15 days, or run stripe events resend within 30 days. A manual resend leaves the automatic retries in place.
Do I need an IP allowlist if I verify signatures?
Stripe recommends both protections together. Signature verification proves that Stripe signed the request, and the allowlist limits which hosts can reach the endpoint.
Should I switch to thin events?
Stripe recommends thin events for new integrations and snapshot events for third-party tools that need the full event object. Stripe asks for a separate destination for thin events, so you can add one next to a working snapshot endpoint and move events across one type at a time.
Summary
Verify the raw body, store the event ID, return 200 and fetch the current object before you act. Test the failure paths with the CLI before launch. If you want a second pair of eyes on a billing integration, AlgoSmiths builds Stripe integrations, subscription management and invoicing as part of SaaS product engineering projects, with weekly demos and a fixed price.
Topic: Backend, data & architecture