# Monitor Stripe webhooks in Next.js with Sentry

> Monitor Stripe webhooks in Next.js with Sentry. Log every event, catch handler failures with resendable event IDs, and alert when deliveries lag or stop.

**URL:** https://sentry.io/cookbook/monitor-stripe-webhooks-nextjs/

---

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.

**Time:** 20-25 minutes | **Difficulty:** Intermediate

## What You'll Learn

- 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

**Topics:** Error Monitoring, Logs, Tracing, Metrics, Dashboards, Alerts

**SDKs:** Next.js

## 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](https://docs.sentry.io/platforms/javascript/guides/nextjs/) `11.0.0` or later (logs and metrics are on by default)

- The [stripe](https://www.npmjs.com/package/stripe) Node library

- The [Stripe CLI](https://docs.stripe.com/cli) for local testing

**Accounts & access**

- [Sentry account](https://sentry.io/signup/) 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

## Steps

### 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.

```typescript
import * 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 });
}
```

[Stripe signature verification](https://docs.stripe.com/webhooks#verify-signature)

### 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.

[Stripe: return a 2xx quickly](https://docs.stripe.com/webhooks#acknowledge-events-immediately)

### 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.

```typescript
import * 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 } });
      }
    }
  });
}
```

[Custom spans in Next.js](https://docs.sentry.io/platforms/javascript/guides/nextjs/tracing/instrumentation/custom-instrumentation/)

### 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.

```bash
stripe 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
```

[Test webhooks locally](https://docs.stripe.com/webhooks#test-webhook)

### 5. Find failing events and resend them

Open [Explore > Logs](https://sentry.io/orgredirect/organizations/:orgslug/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.

```bash
stripe events resend evt_1Q2w3E4r5T6y --webhook-endpoint=we_123
```

[Logs Explorer documentation](https://docs.sentry.io/product/explore/logs/)

### 6. Build a webhook health dashboard

In the [Metrics explorer](https://sentry.io/orgredirect/organizations/:orgslug/explore/metrics/), build each query below and use **Save As** to add it to a new Stripe webhooks dashboard in [Dashboards](https://sentry.io/orgredirect/organizations/:orgslug/dashboards/).

- **Events by result:** `stripe.webhook.event`, sum, grouped by `result`

- **Events by type:** `stripe.webhook.event`, sum, grouped by `stripe.event_type`

- **Delivery lag:** `stripe.webhook.lag` at p95, grouped by `stripe.event_type`

- **Handler duration:** p95 duration of spans with `span.op:stripe.webhook`, from the Trace Explorer

[Dashboards documentation](https://docs.sentry.io/product/dashboards/)

### 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.event` where `result:failed` is 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.lag` above 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.event` volume dropping below its normal pattern. This is the only monitor that fires when Stripe can't reach you, because your app records nothing.

[Monitors documentation](https://docs.sentry.io/product/monitors-and-alerts/monitors/)

## Summary

**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.

## 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.livemode` in your dashboard so test events don't hide a drop in live traffic.

- Subscribe your endpoint only to the event types you handle. Fewer `ignored` events 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 `200` and 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 `created` timestamp. 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'` from `dataCollection.httpBodies` to keep it out.

## FAQ

**Doesn't Stripe already show me failed deliveries?**

Stripe's Event deliveries tab shows whether your endpoint returned a 2xx. It can't see what happens after that. If you acknowledge an event and then fail to fulfill the order, Stripe reports a successful delivery. Sentry covers that gap, plus the code-level detail you need to fix it.

**Why not return a 500 and let Stripe retry?**

You can for fast, simple handlers. But Stripe treats slow responses as failures too, and a handler that times out gets retried while it may still be running. Responding immediately and processing in the background avoids that. If you'd rather rely on Stripe's retries, keep the same logs, metrics, and alerts and return the error status instead.

**Why are signature failures logged instead of captured as errors?**

Invalid signatures come from misconfiguration or from requests that didn't come from Stripe. Neither is a bug in your code. A warning log plus the invalid_signature count lets you chart and alert on them without flooding Issues.

**Does this work with other webhook providers?**

Yes. The pattern of verifying, acknowledging quickly, deduplicating, and recording every result applies to GitHub, Shopify, Twilio, and any other provider that sends webhooks. Change the signature check and the attribute names.

**Why are my Stripe webhooks failing or timing out?**

Stripe expects a quick 2xx response, so slow handlers count as failed deliveries. Acknowledge the event first and do the work in the background. If signature verification fails, check that you read the raw body with `await req.text()` and that no proxy or middleware rewrites it.

**How do Stripe webhook retries work?**

In live mode, Stripe retries a failed delivery with exponential backoff for up to three days. A delivery fails when your endpoint doesn't return a 2xx, so events you acknowledge and then fail to process are not retried. Track event IDs so retried and resent events are processed once.

## Next Steps

- [Metrics dashboards and alerts](/cookbook/custom-metrics-dashboard-alerts-nextjs/): Go deeper on thresholds versus anomaly detection for custom metrics.

- [Structure your logs](/cookbook/structure-your-logs/): Make every log queryable with stable event names and flat attributes.

- [Find out why your Next.js checkout fails silently](/cookbook/debug-silent-checkout-failures-nextjs/): Trace checkout failures that never throw an error back to the request that caused them.

- [product/cron-monitoring](https://sentry.io/product/cron-monitoring/)

---

*Source: [sentry.io/cookbook/monitor-stripe-webhooks-nextjs/](https://sentry.io/cookbook/monitor-stripe-webhooks-nextjs/)*
