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.
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.0or 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.
npx @sentry/wizard@latest -i nextjsAdds the SDK and instrumentation files to your app.
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/],
}),
],
});Records every session with an error and captures request and response bodies for the checkout API.
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.
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.
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
}
}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.
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
}
}The route reports unexpected errors and returns a real error status instead of a 200.
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.completelog carries the details you'd want while debugging a single attempt, like the cart size, payment method, and error code. - A
checkout.attemptmetric counts every attempt byresult, so you can chart and alert on the success rate. - A
finallyblock records the log and metric on every path, success or failure, without repeating them in each branch.
app/api/checkout/route.tsimport * 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 searchmessage: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/checkoutrequest 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.
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.
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.attemptwhereresult:failedrises above a number you'd act on, such as 20 per hour. - Successes disappear: an anomaly alert on
checkout.attemptwhereresult:successdrops below its normal pattern. This catches failures that never reach your server at all.
curl https://cli.sentry.dev/install -fsS | bash
sentry auth loginInstalls the Sentry CLI and its agent skill, then signs you in.
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.Paste this into your coding agent from your project directory.
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
resultanderror.codeto 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
fetchthrows on a 4xx or 5xx. It only rejects on network errors, so always checkres.ok. - ⚠️ Returning
200with{ 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
beforeSendLogto 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'fromdataCollection.httpBodiesinsentry.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
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.networkDetailAllowUrls (step 1). Before you add a route there, make sure its requests and responses don't contain card numbers or other payment details.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.