← Back to Cookbook

Find out why your Next.js checkout fails silently

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.

Features
SDKs
Category Debugging
Time
25-30 minutes
Complexity
Intermediate
Steps
8 steps

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 11.0.0 or later (logs and metrics are on by default)
Accounts & access
  • Sentry account 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

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.

Next.js Session Replay setup
Bash
npx @sentry/wizard@latest -i nextjs

Adds the SDK and instrumentation files to your app.

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.

Capturing errors in Next.js
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
  }
}

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

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.
Next.js logs setup
app/api/checkout/route.ts
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 } });
    }
  });
}

4
Find the failure pattern in the Logs Explorer

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

Logs Explorer documentation
Logs search
message:checkout.complete !checkout.result:success

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

6
Watch what the customer saw in Session Replay

From the trace, open the linked Session Replay. 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

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.

Seer documentation
Ask Seer Agent
Why are checkout attempts failing for EU customers since release 2.14.0?

8
Alert when checkout success drops

Open the Metrics explorer, 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. 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). 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.
Alerts documentation
Bash
curl https://cli.sentry.dev/install -fsS | bash
sentry auth login

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

That's it.

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.

  • 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

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.

Frequently asked questions

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.

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.

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.

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.

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.

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.

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.