# Debug silent checkout failures in Next.js with Sentry

> Find out why your Next.js checkout fails silently. Catch swallowed errors, trace failed payments, watch the session, and alert when success drops.

**URL:** https://sentry.io/cookbook/debug-silent-checkout-failures-nextjs/

---

Your checkout page shows no errors, but orders are down. Surface the failures your code swallows, then use logs, traces, and Session Replay to find the cause, hand it to Seer for a fix, and get alerted the next time checkout success drops.

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

## What You'll Learn

- Found and fixed the code paths that swallowed checkout errors

- Recorded every checkout outcome with a wide log, a span, and a metric

- Grouped failures in the Logs Explorer to find the pattern

- Traced a failed request to the payment provider call

- Watched the customer's experience in Session Replay

- Used Seer to find the regressing commit and propose a fix

- Set up alerts for failure spikes and success drops

**Topics:** Error Monitoring, Logs, Tracing, Session Replay, Metrics, Alerts, Seer

**SDKs:** Next.js

## Before you start

**SDKs & packages**

- A Next.js 14+ app (App Router) with a checkout flow, on Node.js 20.19.0 or later

- [@sentry/nextjs](https://docs.sentry.io/platforms/javascript/guides/nextjs/) `11.0.0` or later (logs and metrics are on by default)

**Accounts & access**

- [Sentry account](https://sentry.io/signup/) with a Next.js project

- Seer enabled and a GitHub repo connected (for step 7)

- Access to deploy your app

**Knowledge**

- Familiarity with Next.js Route Handlers

- A basic idea of how your payment provider reports errors

## Steps

### 1. Turn on logs, tracing, and Session Replay

A silent failure is one your error monitor never hears about. In checkout, it usually comes from one of three patterns: `fetch()` resolving normally on a 4xx or 5xx response, a `catch` block that logs to the console and moves on, or an API route that returns `200` with `{ ok: false }`. This recipe uses a Next.js store where the payment step started failing for some customers after a release, and nothing showed up in Issues.

Run the wizard to add Sentry to your Next.js app. Logs are on by default, so you only need to configure tracing and Replay. Set Replay to record every session that hits an error, and add your checkout API to `networkDetailAllowUrls` so Replay captures the request and response bodies for that route. Replay masks all text and inputs by default, so card details stay out of recordings.

In `sentry.server.config.ts`, set a `tracesSampleRate` as well, so server logs and spans connect to the same trace as the browser session.

**Install**

Adds the SDK and instrumentation files to your app.

```bash
npx @sentry/wizard@latest -i nextjs
```

**Client config**

Records every session with an error and captures request and response bodies for the checkout API.

```typescript
import * as Sentry from "@sentry/nextjs";

Sentry.init({
  dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
  tracesSampleRate: 1.0,
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0, // record every session with an error
  integrations: [
    Sentry.replayIntegration({
      networkDetailAllowUrls: [/\/api\/checkout/],
    }),
  ],
});
```

[Next.js Session Replay setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/session-replay/)

### 2. Stop swallowing checkout errors

Search your checkout code for the places a failure can disappear. Look for `fetch` calls that never check `res.ok`, empty or console-only `catch` blocks, and `.catch(() => {})`. In the example, a declined payment returns a 500, `fetch` doesn't throw, and the user is sent to the confirmation page anyway.

Keep the `try/catch`, but make a bad response throw. A small `CheckoutError` carries the server's error code, so server failures and network errors go through the same `catch` block, which reports them to Sentry with tags you can filter on and tells the user what happened. The client capture is what triggers on-error Replay, so every failed checkout now comes with a session recording attached.

On the server, the checkout route had the same problem. It caught the payment error, logged it to the console, and returned `{ ok: false }` with a `200` status, so neither the browser nor Sentry could tell it failed. Report unexpected errors (expected declines like `card_declined` are recorded in step 3) and return a real error status with a code the browser can read.

**Before**

A 500 response doesn't throw, so the user lands on the confirmation page and Sentry never hears about it.

```typescript
async function handleCheckout() {
  try {
    await fetch("/api/checkout", { method: "POST", body: JSON.stringify(cart) });
    router.push("/order/confirmed"); // runs even on a 500
  } catch (e) {
    console.error(e); // never reaches Sentry
  }
}
```

**After (client)**

Bad responses throw, get reported with tags and a fingerprint per error code, and show the user an error. The finally block re-enables the Pay button either way.

```typescript
import * as Sentry from "@sentry/nextjs";

class CheckoutError extends Error {
  constructor(public code: string, public status: number) {
    super(`Checkout failed: ${code}`);
    this.name = "CheckoutError";
  }
}

async function handleCheckout() {
  setSubmitting(true);
  try {
    const res = await fetch("/api/checkout", { method: "POST", body: JSON.stringify(cart) });
    if (!res.ok) {
      const { code = "unknown" } = await res.json().catch(() => ({}));
      throw new CheckoutError(code, res.status); // turn a bad response into an error
    }
    router.push("/order/confirmed");
  } catch (err) {
    const code = err instanceof CheckoutError ? err.code : "network_error";
    Sentry.captureException(err, {
      tags: { "checkout.step": "submit", "payment.error_code": code },
      fingerprint: ["checkout-failed", code],
    });
    setError("We couldn't complete your order. Please try again or use another card.");
  } finally {
    setSubmitting(false); // re-enable the Pay button either way
  }
}
```

**After (server)**

The route reports unexpected errors and returns a real error status instead of a 200.

```typescript
import * as Sentry from "@sentry/nextjs";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const cart = await req.json();

  try {
    const charge = await payments.charge(cart);
    const order = await createOrder(cart, charge.id);
    return NextResponse.json({ orderId: order.id });
  } catch (err: any) {
    const code = err?.code ?? "unknown";
    if (code !== "card_declined") {
      Sentry.captureException(err, { tags: { "payment.error_code": code } }); // was: console.error(err)
    }
    return NextResponse.json({ code }, { status: 502 });                    // was: { ok: false } with a 200
  }
}
```

[Capturing errors in Next.js](https://docs.sentry.io/platforms/javascript/guides/nextjs/capturing-errors/)

### 3. Record every checkout outcome with a log, a span, and a metric

Some checkout failures never throw an error at all, like a declined payment your code handles, or an order that never gets created. To see the whole picture, record the outcome of every checkout attempt, successful or not.

Build on the checkout route from step 2, then deploy and run a few test checkouts, including one with a card your provider's test mode always declines. A payment that comes back without `succeeded` status never throws, so the updated route checks for it and records it as `declined` with a `402`. It adds four things:

- **A span** around the handler times each checkout and ties its logs and errors to the same trace as the browser session.

- **One wide `checkout.complete` log** carries the details you'd want while debugging a single attempt, like the cart size, payment method, and error code.

- **A `checkout.attempt` metric** counts every attempt by `result`, so you can chart and alert on the success rate.

- **A `finally` block** records the log and metric on every path, success or failure, without repeating them in each branch.

```typescript
import * as Sentry from "@sentry/nextjs";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const cart = await req.json();
  const attributes = {
    "cart.items_total": cart.items.length,
    "cart.total_value_cents": cart.totalCents,
    "payment.method": cart.paymentMethod,
    "user.country": cart.billingCountry,
  };
  let result = "success";
  let errorCode = "none";

  return Sentry.startSpan({ name: "checkout.submit", op: "checkout" }, async (span) => {
    try {
      const charge = await payments.charge(cart); // outgoing HTTP is traced automatically
      if (charge.status !== "succeeded") {
        result = "declined"; // the provider answered, but did not take the payment
        errorCode = charge.status;
        return NextResponse.json({ code: errorCode }, { status: 402 });
      }
      const order = await createOrder(cart, charge.id);
      return NextResponse.json({ orderId: order.id });
    } catch (err: any) {
      const code = err?.code ?? "unknown";
      result = "failed";
      errorCode = code;
      if (code !== "card_declined") {
        Sentry.captureException(err, { tags: { "payment.error_code": code } });
      }
      return NextResponse.json({ code }, { status: 502 });
    } finally {
      span.setAttribute("checkout.result", result);
      const level = result === "failed" ? "error" : "info";
      Sentry.logger[level]("checkout.complete", { ...attributes, "checkout.result": result, "error.code": errorCode });
      Sentry.metrics.count("checkout.attempt", 1, { attributes: { result, "error.code": errorCode } });
    }
  });
}
```

[Next.js logs setup](https://docs.sentry.io/platforms/javascript/guides/nextjs/logs/)

### 4. Find the failure pattern in the Logs Explorer

Open [Explore > Logs](https://sentry.io/orgredirect/organizations/:orgslug/explore/logs/) and filter to checkouts that did not succeed with the query below. Because every outcome uses the same stable message and flat attributes, you can group by any field to see what the failures have in common.

Group by `error.code`, then by `user.country` or `payment.method`. Filter by release to see whether the failures started with a deploy. In the example app, nearly every failure is `authentication_required`, all from EU cards, and they start with release `2.14.0`.

```text
message:checkout.complete !checkout.result:success
```

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

### 5. Open the trace to see where the request broke

Click any failed log and jump to its trace. The trace waterfall shows the full path of that single checkout, from the browser's `fetch` to `POST /api/checkout`, the `checkout.submit` span, and the outgoing call to your payment provider.

Look at the payment provider's span. Its status code and response time tell you whether the failure came from the provider rejecting the request, a timeout, or your own code after the charge. In the example, the provider returns a 402 asking for an extra authentication step, and the checkout route treats it as a hard failure instead of handing it back to the browser.

[Trace view documentation](https://docs.sentry.io/concepts/key-terms/tracing/trace-view/)

### 6. Watch what the customer saw in Session Replay

From the trace, open the linked [Session Replay](https://sentry.io/orgredirect/organizations/:orgslug/explore/replays/). Replay shows the checkout from the customer's side, so you can measure the impact as well as the cause. If Replay was already running before the fix, a session-sampled replay shows the user landing on a confirmation page for an order that doesn't exist; after the fix, they see a clear error and can try again.

In the replay, check:

- **Network tab:** the `POST /api/checkout` request with its 502 status and the `{ code: "authentication_required" }` response body.

- **Timeline:** what the user did next, such as retrying, switching cards, rage-clicking the Pay button, or leaving.

- **Console and breadcrumbs:** any client-side warnings that led up to the failure.

[Session Replay documentation](https://docs.sentry.io/product/session-replay/)

### 7. Hand the root cause to Seer

Because these failures were silent, there's no long-standing issue waiting for you in the Issues feed. Start from what you found instead. Ask Seer Agent, in Sentry or Slack, about the pattern from the Logs Explorer. Seer reasons over your logs, traces, and repository, so it doesn't need an existing issue to work from. Once the error capture from step 2 is deployed, new failures also create an issue, and you can run Seer's root cause analysis from there.

In the example, Seer points to the commit in `2.14.0` that removed the client-side handler for the provider's extra authentication step, and proposes a fix that returns the authentication challenge to the browser instead of failing the order. Review the plan, then let Seer open a pull request or send the fix to your coding agent.

- **Ask Seer Agent**: `Why are checkout attempts failing for EU customers since release 2.14.0?`

[Seer documentation](https://docs.sentry.io/product/ai-in-sentry/seer/)

### 8. Alert when checkout success drops

Open the [Metrics explorer](https://sentry.io/orgredirect/organizations/:orgslug/explore/metrics/), select `checkout.attempt`, and group by `result`. Use **Save As** to add it to a checkout dashboard, then create monitors from it. Route them to the channel your on-call team watches. Ship Seer's fix, confirm the failures stop in the Logs Explorer, and mark the issue resolved in the next release so Sentry flags it if it comes back.

If you use a coding agent like Claude Code, Cursor, or Codex, it can create the dashboard and the threshold alert for you with the [Sentry CLI](https://cli.sentry.dev/). Install the CLI, which also installs its agent skill, sign in, then give your agent the prompt below from your project directory. It reads your code to confirm the metric and attribute names, then runs the matching `sentry dashboard` and `sentry alert` commands. Review each dry run before you let it apply the change.

The CLI has no anomaly option, so create the anomaly monitor in the UI (see [Metrics dashboards and alerts](/cookbook/custom-metrics-dashboard-alerts-nextjs/)). Either way, set up two monitors:

- **Failures spike:** a threshold alert on `checkout.attempt` where `result:failed` rises above a number you'd act on, such as 20 per hour.

- **Successes disappear:** an anomaly alert on `checkout.attempt` where `result:success` drops below its normal pattern. This catches failures that never reach your server at all.

**Install the CLI**

Installs the Sentry CLI and its agent skill, then signs you in.

```bash
curl https://cli.sentry.dev/install -fsS | bash
sentry auth login
```

**Agent prompt**

Paste this into your coding agent from your project directory.

```text
Using the Sentry CLI, create a "Checkout health" dashboard for this project with a widget showing the checkout.attempt metric summed and grouped by result. Then create one threshold alert that notifies #checkout-oncall when checkout.attempt with result:failed goes above 20 in an hour. Do not create an anomaly alert; I will set that up in the UI. Show me each command with --dry-run before you run it.
```

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

## Summary

**Checkout failures aren't so silent anymore.**

Every checkout attempt now leaves a log, a trace, a metric, and, when it fails, an error and a replay. You know why the failures happened, you have a fix, and you'll hear about the next one before your revenue report does.

## Pro Tips

- Log at the end of the checkout, not the start. The outcome, error code, and order ID only exist at the end.

- Keep `result` and `error.code` to a small set of values so they group and chart cleanly.

- Alert on missing successes as well as on failures. A broken Pay button produces zero errors and zero successes.

- Tag the release in your Sentry config so you can tie a failure spike to the deploy that caused it.

## Common Pitfalls

- Assuming `fetch` throws on a 4xx or 5xx. It only rejects on network errors, so always check `res.ok`.

- Returning `200` with `{ ok: false }` from your API. Sentry's tracing and your client both read that as success.

- Logging card numbers, CVCs, or full addresses. Pick explicit fields and use `beforeSendLog` to redact anything sensitive. SDK v11 attaches incoming request bodies to server events by default. If your checkout request carries card or address data, remove `'incomingRequest'` from `dataCollection.httpBodies` in `sentry.server.config.ts`.

- Expecting a replay for errors you never capture. On-error Replay only records when Sentry sees an error event.

## FAQ

**Users report a checkout bug you can't reproduce. How do you debug it?**

Start from the failed `checkout.complete` log and open its trace to see which call broke. Then open the linked Session Replay to watch what the customer saw and did. This recipe sets up all three, so one failed checkout gives you the log, the trace, and the replay.

**What counts as a silent failure?**

Any failure your users notice but your monitoring doesn't. In checkout, that's usually a caught exception that never gets reported, an HTTP error the client ignores, or an API that returns success when the operation failed.

**Why use a log and a metric for the same event?**

They answer different questions. The metric gives you a cheap, fast success rate to chart and alert on. The log carries the detail you need to investigate a single failure, like the cart, payment method, and error code, and links to its trace.

**Will Session Replay record card details?**

Not with the default settings. Replay masks all text and input values unless you change that. Replay can also record the full request and response for specific API routes, but only the ones you list in `networkDetailAllowUrls` (step 1). Before you add a route there, make sure its requests and responses don't contain card numbers or other payment details.

**Does this work outside Next.js?**

Yes. The same pattern of checking responses, capturing errors, logging outcomes, and counting attempts works with any Sentry SDK that supports logs and metrics, including React, Node.js, and Python.

**Do I need Seer for this recipe?**

No. Steps 1 through 6 and step 8 find and monitor the problem without Seer. Seer speeds up step 7 by connecting the failure to the code change behind it.

## Next Steps

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

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

- [Monitor Stripe webhooks with Sentry](/cookbook/monitor-stripe-webhooks-nextjs/): Catch the failed and missing webhooks that leave paid orders unfulfilled.

---

*Source: [sentry.io/cookbook/debug-silent-checkout-failures-nextjs/](https://sentry.io/cookbook/debug-silent-checkout-failures-nextjs/)*
