Verify each webhook signature on the raw body in a Route Handler, store the event id under a unique constraint, return 2xx fast and process in a worker. Fulfil only from verified events or server-side API checks, never the redirect, and reconcile with the provider.
Must-have checklist
Must
Verify every webhook with the provider SDK against the exact body from await request.text(); never verify JSON.stringify(await request.json()).
Re-serialised JSON changes the bytes, so real events fail and teams are tempted to switch verification off.
Keep Stripe's signature timestamp tolerance (SDK default 5 minutes, never 0). Razorpay signs no timestamp, so reject event ids you have already stored.
Stops a captured, validly signed request from being replayed.
Insert each event into a table with a unique (provider, event_id) key using ON CONFLICT DO NOTHING; Razorpay's id is the x-razorpay-event-id header.
Both providers deliver at least once and retry, so duplicates are expected.
Return 2xx right after verifying and storing the event; run fulfilment, emails and provider API calls in a queue or background job.
Razorpay times out after 5 seconds and Stripe counts timeouts as failures; both then retry.
Fulfil orders only from verified webhooks or a server-side API fetch of the payment; never from the success redirect or a client-side callback alone.
Customers may never reach the landing page, and anything the browser sends can be forged.
Make fulfilment idempotent with a unique constraint per order, so webhook and landing-page calls running at the same time grant access once.
Stripe warns fulfilment may be called multiple times, possibly concurrently, for one payment.
Store payment status as an explicit state machine in Postgres and apply only allowed transitions, for example never from succeeded back to pending.
Events arrive out of order; a late or duplicate event must not undo a success.
Run a scheduled job that compares recent provider payments with your payments table and repairs missing or stuck rows.
Retries stop (Stripe after up to 3 days live, Razorpay after 24 hours) and a lost event is otherwise never noticed.
Use separate API keys and webhook secrets for test and live mode in server-only environment variables; reject Stripe events whose livemode does not match.
Keep the webhook route out of proxy.ts auth redirects, CSRF checks and trailing-slash redirects; register the exact final URL.
Stripe counts 3xx responses as failed deliveries, and Razorpay accepts only 2xx.
Should
Before acting on an event, fetch the current payment, session or subscription from the provider API instead of trusting the payload order.
Accept the old and the new webhook secret during rotation, and rotate when a secret may have leaked or someone with access leaves.
Stripe keeps the old secret valid for up to 7 days; Razorpay retries of older events still carry the old signature.
Subscribe only to the event types you handle, and return 2xx for any other type instead of an error.
Errors for ignored types cause pointless retries and can get the endpoint disabled.
Where your host supports it, also allowlist the provider's published webhook IPs; never use it instead of signature checks.
Alert on signature failures, a growing backlog of unprocessed events and disabled endpoints.
Razorpay disables a webhook after 24 hours of failed deliveries.
Decisions to make
Asked before building01Which payment provider(s) will send webhooks?
02Are you selling one-time payments, subscriptions, or both?
03Do you already run a queue or background job runner?
04Will the app run on serverless functions or a long-running server?
05Will you accept payment methods that confirm later, such as bank debits or bank transfers?
Options
3 comparedPostgres event table drained by a worker
Examples, not endorsements: pg-boss, Graphile Worker
- You already run Postgres and want no extra infrastructure
- You want the event log and payment state updated in one transaction
- You have no way to run a worker or scheduled trigger
- Event volume is high enough to strain the primary database
- You own retries, backoff and dead-letter handling
- Workers poll the table, adding some database load
Managed queue or durable job service
Examples, not endorsements: Inngest, Trigger.dev, Amazon SQS, Upstash QStash
- You run on serverless functions and expect bursts (for example month-start renewals)
- You want built-in retries, backoff and a dashboard
- Strict data-residency rules forbid sending payloads to another vendor
- Another vendor and a per-message or per-run fee
- You still record and deduplicate events in Postgres
Inline processing with after()
- Low-volume prototypes where fulfilment is quick and idempotent
- Any work that must not be lost
- No retry if the callback fails; reconciliation is the only safety net
- Bounded by the route's max duration on your platform
Why this approach
A verified webhook is the only reliable signal that money moved, because customers can close the tab before your success page loads and some payment methods settle later. Verifying the signature on the raw body, recording the event id once in Postgres and returning 2xx quickly keeps the endpoint safe under the providers' at-least-once retries. A Postgres event table drained by a worker adds no new infrastructure and lets you record events and payment state in one transaction. Choose a managed queue when you run on serverless functions and expect bursts, and use inline after() processing only for low-volume prototypes backed by a reconciliation job.
Lenses
Treat the webhook URL as public: anyone can POST to it, so the signature is the only proof of origin. Read the body once as text, verify it with the provider SDK, and only then parse JSON. Stripe signs a timestamp, so keep the SDK's 5-minute tolerance and keep server clocks in sync. Razorpay signs no timestamp, so the stored event id is your replay guard. Keep test and live secrets in server-only environment variables, never with a NEXT_PUBLIC_ prefix (Next.js inlines those into browser bundles). During rotation, accept both secrets until retries signed with the old one have stopped. Never grant access from a redirect's query string; fetch the session or payment from the provider API on the server. Exclude the route from proxy.ts session checks: the signature replaces them.
Version notes
- Snapshot destinations:
stripe.webhooks.constructEvent(rawBody, signature, secret). Thin destinations (Stripe's recommended format):stripe.parseEventNotification(...). Since v21 the wrong method for the format throws. - The default signature tolerance is 300 seconds; never pass 0, which disables the timestamp check.
- v23 requires Node.js 20 or later; since v22 the default export is a true class, so create the client with
new Stripe(key). - Each major pins a newer API version (23.1.0 pins
2026-10-28.endive); snapshot payloads follow the destination's API version, not the SDK's. - Never use the
...WithoutVerificationparsing helpers outside tests.
validateWebhookSignature(rawBody, signature, secret)(alsoRazorpay.validateWebhookSignature) returns a boolean; pass the raw text, notJSON.stringifyof a parsed body as some doc snippets do.- Webhook signatures carry no timestamp; replay protection relies on storing
x-razorpay-event-idunder a unique constraint. - The helper compares with
===; for a constant-time check, compute HMAC-SHA256 withnode:cryptoand compare withtimingSafeEqual. - Verify Checkout results with
validatePaymentVerification({ order_id, payment_id }, signature, keySecret), using the order id stored on your server.
- Read the body once with
await request.text()in aPOSTRoute Handler; App Router handlers need nobodyParserconfig. - Keep the default Node.js runtime; the 16.x docs mark the Edge runtime as deprecated.
after()runs work after the response, within the route's max duration, but never retries; use it only to nudge a durable worker.- Exclude webhook paths from
proxy.tsmatchers so auth redirects never answer the provider.
Verify checks
A request with a missing or wrong signature header gets 400 and writes nothing to the database.
A validly signed payload with unusual JSON whitespace passes verification, proving the handler verifies the raw body rather than re-serialised JSON.
A Stripe payload signed with a timestamp older than the tolerance is rejected.
Delivering the same event id twice returns 2xx both times and fulfils the order once.
Delivering a failure or pending event after a success event leaves the payment in the succeeded state.
Webhook and success-page fulfilment running concurrently for the same payment create exactly one fulfilment row.
Visiting the success URL with a made-up session or payment id does not fulfil any order.
With the worker stopped, the handler still returns 2xx in under 1 second and leaves the event stored as unprocessed.
When processing throws, the event stays unprocessed with an incremented attempt count and is retried later.
A payment that is paid at the provider but missing locally (webhook never delivered) is repaired by the reconciliation job.
A test-mode deployment rejects a Stripe event with livemode true, and a live deployment rejects livemode false.
A POST to the webhook URL without a session cookie never receives a 3xx response.
Common mistakes
- Calling
request.json()and re-serialising before verification, then disabling verification when it fails. - Fulfilling from the success redirect or a client-side Checkout callback.
- Deduplicating on
createdtimestamps, or assuming events arrive in order. - Doing slow work (emails, provider API calls, PDFs) before returning 2xx, which causes timeouts and duplicate retries.
- Using the test-mode secret in production, or one secret for several endpoints.
- Passing a tolerance of 0 to Stripe's verifier, which turns off replay protection.
- Returning an error for event types you don't handle instead of 2xx.
- Putting the webhook route behind session auth in
proxy.ts, so providers receive redirects. - Treating
after()as a durable queue. - No reconciliation job, so a webhook lost after the retry window is never noticed.