Monitor Stripe webhooks in Next.js with Sentry
Stripe webhooks fulfill orders, renew subscriptions, and flag failed payments. When one breaks, it often doesn't throw an error, so nothing reaches your monitoring and you might not find out for days. Track every event your Next.js app receives, catch handler failures with the event ID you need to resend them, and get alerted when events slow down or stop arriving.
Before you start
SDKs & packages
- A Next.js app on Node.js 20.19.0 or later (App Router, 15.1 or later for
after()) - @sentry/nextjs
11.0.0or later (logs and metrics are on by default) - The stripe Node library
- The Stripe CLI for local testing
Accounts & access
- Sentry account with a Next.js project
- Stripe account with a webhook endpoint and its
whsec_signing secret
Knowledge
- Familiarity with Next.js Route Handlers
- A basic understanding of how Stripe events and retries work
1 Verify the signature and tag every event
Webhook handlers fail differently from the rest of your app: often no error is thrown at all, Stripe retries failed deliveries for up to three days in live mode, events can arrive more than once and out of order, and if Stripe can't reach your endpoint your app logs nothing.
Start by creating the webhook route. Read the body with req.text() so the signature check gets the raw payload, then verify it with your signing secret. Rejected requests get a warning log and a count, not an exception. A sudden spike usually means a rotated secret or a proxy rewriting the body, and you want to see it without filling Issues with noise. The event type and ID tags ride along on every error from this request, so each issue tells you exactly which Stripe event to resend.
app/api/webhooks/stripe/route.tsimport * as Sentry from "@sentry/nextjs";
import Stripe from "stripe";
import { after } from "next/server";
import { processEvent } from "@/lib/stripe-webhooks";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(req: Request) {
const body = await req.text(); // raw body, required for verification
const signature = req.headers.get("stripe-signature") ?? "";
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
} catch (err) {
Sentry.logger.warn("stripe.webhook.rejected", { "error.message": (err as Error).message });
Sentry.metrics.count("stripe.webhook.event", 1, { attributes: { result: "invalid_signature" } });
return new Response("Invalid signature", { status: 400 });
}
Sentry.setTags({ "stripe.event_type": event.type, "stripe.event_id": event.id });
after(async () => {
await processEvent(event); // step 2
await Sentry.flush(2000); // the SDK already flushed when the response was sent
});
return Response.json({ received: true });
}
2 Respond fast and process in the background
Stripe expects a 2xx quickly and counts slow responses as failed deliveries. The route above returns right away and hands the work to Next.js after(), which runs once the response is sent. The SDK flushes its queue when the response is sent, before after() runs, so call Sentry.flush() at the end of the callback. Otherwise the log, metrics, and late spans can be lost on serverless platforms.
This changes what a failure looks like. Stripe already got its 200, so it won't retry an event your handler fails to process. Sentry becomes the place you find out, which is why the next step records every outcome. For high volume or work that must not be lost, push the event onto a durable queue instead and keep the same instrumentation in the worker.
3 Record every event's outcome
Wrap processing in a span, skip events you've already handled, and finish with one log and two metrics, whatever the result. Use a small, fixed set of results: processed, duplicate, ignored, or failed. Measure delivery lag, the time between Stripe creating the event and your app handling it. Lag climbs when Stripe is retrying or your endpoint is backed up, often before anything fails outright.
markProcessed and unmarkProcessed stand in for your own storage, such as a table with a unique constraint on the event ID. Stripe recommends tracking event IDs to catch duplicate deliveries. fulfillOrder and markSubscriptionPastDue are your own application functions too.
lib/stripe-webhooks.tsimport * as Sentry from "@sentry/nextjs";
import type Stripe from "stripe";
export async function processEvent(event: Stripe.Event) {
const attrs = {
"stripe.event_id": event.id,
"stripe.event_type": event.type,
"stripe.livemode": event.livemode,
};
const lagMs = Date.now() - event.created * 1000;
await Sentry.startSpan({ name: `stripe.webhook ${event.type}`, op: "stripe.webhook", attributes: attrs }, async () => {
let result = "processed";
try {
if (!(await markProcessed(event.id))) { result = "duplicate"; return; }
switch (event.type) {
case "checkout.session.completed":
await fulfillOrder(event.data.object); break;
case "invoice.payment_failed":
await markSubscriptionPastDue(event.data.object); break;
default:
result = "ignored";
}
} catch (err) {
result = "failed";
await unmarkProcessed(event.id); // so a resend isn't skipped as a duplicate
Sentry.captureException(err, { tags: { "stripe.event_type": event.type, "stripe.event_id": event.id } });
} finally {
const level = result === "failed" ? "error" : "info";
Sentry.logger[level]("stripe.webhook.processed", { ...attrs, "webhook.result": result, "webhook.lag_ms": lagMs });
Sentry.metrics.count("stripe.webhook.event", 1, { attributes: { "stripe.event_type": event.type, "stripe.livemode": event.livemode, result } });
if (result !== "duplicate") {
Sentry.metrics.distribution("stripe.webhook.lag", lagMs, { unit: "millisecond", attributes: { "stripe.event_type": event.type, "stripe.livemode": event.livemode } });
}
}
});
}
4 Send test events with the Stripe CLI
Forward events to your local server, trigger a few, and resend one to check that duplicates are caught. To see a failure end to end, make fulfillOrder throw temporarily and trigger a checkout event. stripe listen prints a temporary signing secret. Use it as STRIPE_WEBHOOK_SECRET while you test locally.
Terminalstripe listen --forward-to localhost:3000/api/webhooks/stripe
stripe trigger checkout.session.completed
stripe trigger invoice.payment_failed
stripe events resend evt_123 # use an evt_ ID from the trigger output; should log result: duplicate
5 Find failing events and resend them
Open Explore > Logs and filter to webhook outcomes with message:stripe.webhook.processed. Group by stripe.event_type and webhook.result to see which events fail, which ones you're ignoring, and how many are duplicates. Add webhook.result:failed to the filter to list only the failures.
Open any failed log to jump to its trace. The span shows how long the handler ran and every database and API call inside it, so you can see whether the failure came from your code, your database, or a call back to Stripe.
Each handler failure also creates an issue tagged with stripe.event_type and stripe.event_id. After you ship a fix, resend the failed events. Because the handler cleared their IDs, the resends are processed instead of skipped as duplicates. Stripe allows a manual resend up to 30 days after an event was created through the CLI, and up to 15 days through the Dashboard.
Terminalstripe events resend evt_1Q2w3E4r5T6y --webhook-endpoint=we_123
6 Build a webhook health dashboard
In the Metrics explorer, build each query below and use Save As to add it to a new Stripe webhooks dashboard in Dashboards.
- Events by result:
stripe.webhook.event, sum, grouped byresult - Events by type:
stripe.webhook.event, sum, grouped bystripe.event_type - Delivery lag:
stripe.webhook.lagat p95, grouped bystripe.event_type - Handler duration: p95 duration of spans with
span.op:stripe.webhook, from the Trace Explorer
7 Alert on failures, lag, and silence
Create three metric monitors from your saved metric queries and route them to the channel that owns billing. When the silence alert fires, check the endpoint's Event deliveries tab in Stripe Workbench. It shows the status code or connection error for each attempt Stripe made.
Resending events after a fix raises the p95 lag for a while, because resent events keep their original created time. Expect the lag monitor to fire after a large resend.
- Handlers failing: metric monitor with a fixed threshold on
stripe.webhook.eventwhereresult:failedis above 0 in 10 minutes. Payment events are rare enough that one failure is worth a look. - Deliveries lagging: metric monitor with a fixed threshold on p95
stripe.webhook.lagabove 5 minutes. This usually means Stripe is retrying deliveries that failed or timed out. - Events stopped: metric monitor with dynamic (anomaly detection) thresholds on
stripe.webhook.eventvolume dropping below its normal pattern. This is the only monitor that fires when Stripe can't reach you, because your app records nothing.
That's it.
Your Stripe webhooks are no longer a black box.
Every event leaves a log, a span, and metrics. Failures arrive as issues with the event ID you need to resend them, and you'll hear about lag or missing events before your customers or your finance team do.
- Verified signatures and tagged every event with its type and ID
- Responded to Stripe immediately and processed events in the background
- Recorded each event's result and delivery lag
- Tested handling, failures, and duplicates with the Stripe CLI
- Found failing events in the Logs Explorer, traced them, and resent them after a fix
- Built a dashboard and alerts for failures, lag, and silence
Pro tips
- 💡 Store the Sentry trace ID in your PaymentIntent or Checkout Session
metadata, then add it as an attribute in the webhook handler. You can then search for the checkout request that started it. - 💡 Split
stripe.livemodein your dashboard so test events don't hide a drop in live traffic. - 💡 Subscribe your endpoint only to the event types you handle. Fewer
ignoredevents means cleaner volume alerts. - 💡 Set a release in your Sentry config so a spike in failures lines up with the deploy that caused it.
Common pitfalls
- ⚠️ Parsing the body as JSON before verifying it. Any change to the raw body breaks the signature check, so always use
req.text(). - ⚠️ Returning
200and then failing quietly in the background. Stripe won't retry, so capture the error and keep the event ID. - ⚠️ Relying on event order or the
createdtimestamp. Stripe doesn't guarantee order, and events can share a timestamp. - ⚠️ Logging the full event payload. It can contain customer names, emails, and addresses. Pick the fields you need. SDK v11 also attaches the incoming request body, the full Stripe event, to server events by default. Remove
'incomingRequest'fromdataCollection.httpBodiesto keep it out.
Frequently asked questions
await req.text() and that no proxy or middleware rewrites it.What's next?
Fix it, don't observe it.
Get started with the only application monitoring platform that empowers developers to fix application problems without compromising on velocity.