Mustlist

Payment webhooks (Stripe, Razorpay) for a Next.js + Postgres app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

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.

Forweb-appsaase-commercemarketplace
Not forstatic-site-without-backendmanual-invoicing-only

Must-have checklist

10 must · 5 should

Must

01

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.

Security
02

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.

Security
03

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.

Data
04

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.

Performance
05

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.

Security
06

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.

Data
07

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.

Data
08

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.

Data
09

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.

Security
10

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.

Security

Should

11

Before acting on an event, fetch the current payment, session or subscription from the provider API instead of trusting the payload order.

Data
12

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.

Security
13

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.

Performance
14

Where your host supports it, also allowlist the provider's published webhook IPs; never use it instead of signature checks.

Security
15

Alert on signature failures, a growing backlog of unprocessed events and disabled endpoints.

Razorpay disables a webhook after 24 hours of failed deliveries.

Performance

Decisions to make

Asked before building

01Which 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 compared
Recommended

Postgres event table drained by a worker

Examples, not endorsements: pg-boss, Graphile Worker

Best fit when
  • You already run Postgres and want no extra infrastructure
  • You want the event log and payment state updated in one transaction
Avoid when
  • You have no way to run a worker or scheduled trigger
  • Event volume is high enough to strain the primary database
Trade-offs
  • 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

Best fit when
  • You run on serverless functions and expect bursts (for example month-start renewals)
  • You want built-in retries, backoff and a dashboard
Avoid when
  • Strict data-residency rules forbid sending payloads to another vendor
Trade-offs
  • Another vendor and a per-message or per-run fee
  • You still record and deduplicate events in Postgres

Inline processing with after()

Best fit when
  • Low-volume prototypes where fulfilment is quick and idempotent
Avoid when
  • Any work that must not be lost
Trade-offs
  • 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

stripe>=23.0.0 <24.0.0
  • 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 ...WithoutVerification parsing helpers outside tests.
Official docsContext7docs.stripe.com
razorpay>=2.0.0 <3.0.0
  • validateWebhookSignature(rawBody, signature, secret) (also Razorpay.validateWebhookSignature) returns a boolean; pass the raw text, not JSON.stringify of a parsed body as some doc snippets do.
  • Webhook signatures carry no timestamp; replay protection relies on storing x-razorpay-event-id under a unique constraint.
  • The helper compares with ===; for a constant-time check, compute HMAC-SHA256 with node:crypto and compare with timingSafeEqual.
  • Verify Checkout results with validatePaymentVerification({ order_id, payment_id }, signature, keySecret), using the order id stored on your server.
next>=16.0.0 <17.0.0
  • Read the body once with await request.text() in a POST Route Handler; App Router handlers need no bodyParser config.
  • 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.ts matchers so auth redirects never answer the provider.

Verify checks

12 checks
01

A request with a missing or wrong signature header gets 400 and writes nothing to the database.

integrationSecurity
02

A validly signed payload with unusual JSON whitespace passes verification, proving the handler verifies the raw body rather than re-serialised JSON.

integrationSecurity
03

A Stripe payload signed with a timestamp older than the tolerance is rejected.

unitSecurity
04

Delivering the same event id twice returns 2xx both times and fulfils the order once.

integrationData
05

Delivering a failure or pending event after a success event leaves the payment in the succeeded state.

integrationData
06

Webhook and success-page fulfilment running concurrently for the same payment create exactly one fulfilment row.

integrationData
07

Visiting the success URL with a made-up session or payment id does not fulfil any order.

e2eSecurity
08

With the worker stopped, the handler still returns 2xx in under 1 second and leaves the event stored as unprocessed.

integrationPerformance
09

When processing throws, the event stays unprocessed with an incremented attempt count and is retried later.

integrationPerformance
10

A payment that is paid at the provider but missing locally (webhook never delivered) is repaired by the reconciliation job.

integrationData
11

A test-mode deployment rejects a Stripe event with livemode true, and a live deployment rejects livemode false.

unitSecurity
12

A POST to the webhook URL without a session cookie never receives a 3xx response.

integrationSecurity

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 created timestamps, 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.

Sources

13 sources