Most Next.js and Stripe tutorials build the same thing. A Server Action creates a Checkout Session, the buyer pays on Stripe's page, a route handler catches checkout.session.completed, and the guide ends. It's a correct demo. It's also about a third of the job.
Stripe's own fulfillment guide lists six things a fulfillment function has to do: survive being called more than once, take a session ID, fetch the session with its line items, check whether it's actually paid, fulfill, and record that it did. The tutorial version usually does two of them. The rest show up in production, roughly in the order below.
This post walks through each gap with App Router code that fixes it, then shows the same store on Flint, where most of this list is the API's job instead of yours.
The gaps at a glance#
| Gap | What breaks | The fix |
|---|---|---|
| The browser sends prices | Anyone can buy at a price they typed | The server looks up every price from IDs |
| The success page fulfills | Paid orders go missing when the tab closes | Fulfill from the webhook |
| The body gets parsed first | Every signature check fails | Verify request.text() before parsing |
completed is treated as paid | Bank debits ship before they settle | Check payment_status, handle the async events |
| Events arrive twice, out of order | Orders ship twice | A unique constraint, and re-read the session |
| Line items aren't in the event | Nobody knows what to ship | Retrieve the session with line_items expanded |
| There's no order object | Refunds, stock, and payouts have nothing to attach to | Design an orders table, or use an API that has one |
The tutorial version#
Here's the shape most guides end on, condensed:
// app/checkout/actions.ts (the tutorial version)
"use server";
import { redirect } from "next/navigation";
import { stripe } from "@/lib/stripe";
export async function checkout(cart: { name: string; price: number; quantity: number }[]) {
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: cart.map((item) => ({
price_data: {
currency: "usd",
product_data: { name: item.name },
unit_amount: item.price, // from the browser
},
quantity: item.quantity,
})),
success_url: `${process.env.APP_URL}/thanks?session_id={CHECKOUT_SESSION_ID}`,
});
redirect(session.url!);
}
The success page then reads session_id, marks the order paid, and sends the confirmation email. Every problem below is in those two files.
1. The browser chose the price#
unit_amount: item.price comes from the cart the browser sent. A Server Action looks like a function call, but it's an HTTP endpoint. The Next.js data security guide is direct about it: an exported Server Action "is reachable via a direct POST request, not just through your application's UI", and you "should always validate input from client, as they can be easily modified."
So anyone who replays that request with price: 100 buys your $128 shoes for a dollar. Stripe charges what it's told to charge. It has no way to know the number is wrong.
The pattern spreads because price_data and price sit side by side in Stripe's API and look equally official. Inline price_data has real uses, such as a custom quote your server computed. Fed from the browser, it's the bug.
The browser should send only IDs and quantities. The server decides everything else:
// app/checkout/actions.ts
"use server";
import { redirect } from "next/navigation";
import { z } from "zod";
import { db } from "@/lib/db";
import { stripe } from "@/lib/stripe";
const Cart = z
.array(z.object({ sku: z.string(), quantity: z.number().int().min(1).max(10) }))
.min(1)
.max(100); // Checkout's limit in payment mode
export async function checkout(input: unknown) {
const cart = Cart.parse(input);
const prices = await db.activePricesBySku(cart.map((item) => item.sku));
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: cart.map((item) => {
const price = prices.get(item.sku);
if (!price) throw new Error(`Unknown or inactive SKU: ${item.sku}`);
return { price: price.stripePriceId, quantity: item.quantity };
}),
success_url: `${process.env.APP_URL}/thanks?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.APP_URL}/cart`,
});
redirect(session.url!); // outside any try/catch: redirect() works by throwing
}
Two App Router details are easy to miss here. redirect() from next/navigation works by throwing, so a try/catch around it swallows the redirect. And session.url is the only supported way to send the buyer to Checkout now: Stripe removed redirectToCheckout from Stripe.js in its 2025-09-30 release, which breaks a lot of older tutorials. The fix for that error covers both client and server redirects.
Keeping prices server-side means you now maintain a catalog: products, variants, and Stripe Price IDs in your own database, kept in sync with Stripe. Stripe shopping cart for multiple products covers the cart side of that, including the 100-line and one-discount limits.
2. The success page isn't a receipt#
Tutorials mark the order paid on /thanks. Stripe's guide explains why that loses orders:
You can't rely on triggering fulfillment only from your Checkout landing page, because your customers aren't guaranteed to visit that page. For example, someone can pay successfully in Checkout and then lose their connection to the internet before your landing page loads.
The money moves and the order never gets created. It works the other way too: anyone can open /thanks?session_id=... directly, so the page has to treat the ID as a claim to check, not proof.
Stripe recommends fulfilling from both the webhook and the landing page, with the landing page as a fast path. In the App Router that means a database write inside a Server Component render, which Next's own guide advises against: mutations "should never be a side-effect" of rendering. There's a simpler option. When a webhook endpoint listens for checkout.session.completed and the session has a success_url, Checkout waits up to 10 seconds for your endpoint to respond before it redirects the buyer. By the time they land, the webhook has usually run. So let the page read, and let the webhook write:
// app/thanks/page.tsx
import { stripe } from "@/lib/stripe";
export default async function Thanks({
searchParams,
}: {
searchParams: Promise<{ session_id?: string }>;
}) {
const { session_id } = await searchParams;
if (!session_id) return <p>We couldn't find that checkout.</p>;
const session = await stripe.checkout.sessions.retrieve(session_id);
return session.payment_status === "unpaid" ? (
<p>Your bank payment is processing. We'll email you when it clears.</p>
) : (
<p>Thanks! Your order is confirmed.</p>
);
}
Keep personal details off this page unless the visitor is signed in. The session ID in the URL is the only thing it checks, and that URL ends up in browser history and analytics.
One local-testing quirk: with stripe listen, Checkout redirects to success_url immediately instead of waiting. A handler that's slow in production can look fine on your laptop.
3. Verify the signature on the raw body#
The webhook route has to verify Stripe's signature against the exact bytes Stripe sent. In the App Router, a route handler receives a standard Web Request, and nothing parses the body until you do. Read it with request.text(). Calling request.json() first, or re-serializing the parsed object, changes the bytes and fails every check with "No signatures found matching the expected signature for payload". That error's reference page catalogs its three usual causes.
// app/api/stripe/webhook/route.ts
import type Stripe from "stripe";
import { stripe } from "@/lib/stripe";
import { fulfillCheckout, notifyPaymentFailed } from "@/lib/fulfill";
export async function POST(request: Request) {
const body = await request.text(); // the exact bytes Stripe signed
const signature = request.headers.get("stripe-signature") ?? "";
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!);
} catch {
return new Response("Invalid signature", { status: 400 });
}
switch (event.type) {
case "checkout.session.completed":
case "checkout.session.async_payment_succeeded":
await fulfillCheckout(event.data.object.id);
break;
case "checkout.session.async_payment_failed":
await notifyPaymentFailed(event.data.object.id);
break;
}
return new Response(null, { status: 200 });
}
Advice written for the Pages Router, export const config = { api: { bodyParser: false } }, still circulates and does nothing here. The Next.js route handler reference says so: "unlike API Routes with the Pages Router, you do not need to use bodyParser".
Respond fast. Stripe asks for a 2xx "before any complex logic that might cause a timeout", and Checkout's redirect is waiting on you. It's tempting to reach for Next's after() to do the work after responding, but after() is built for logging and analytics. If fulfillment fails inside it, Stripe already has its 200 and won't retry. Do one durable write, such as a row in a jobs table, before responding, and let a worker do the slow parts.
4. "Completed" doesn't mean "paid"#
This is the gap that costs real money, and most tutorials skip it.
checkout.session.completed fires when the buyer finishes Checkout. For payment methods with delayed notification, such as ACH Direct Debit and other bank transfers, Stripe's guide says the funds "won't be immediately available when Checkout completes." The session arrives with payment_status: "unpaid", and the payment can still fail days later. Fulfill on completed alone and you ship goods against money that may never arrive.
Stripe resolves it with two more events: checkout.session.async_payment_succeeded and checkout.session.async_payment_failed. The route above already routes them. The other half is in the fulfillment function, which fetches the session and checks its status, because completed fires for instant and delayed methods alike:
// lib/fulfill.ts
import "server-only";
import type Stripe from "stripe";
import { stripe } from "@/lib/stripe";
import { db } from "@/lib/db";
export async function fulfillCheckout(sessionId: string) {
// Re-read the session instead of trusting the event payload.
const session = await stripe.checkout.sessions.retrieve(sessionId, {
expand: ["line_items"],
});
// Bank debits complete as "unpaid" and settle later.
if (session.payment_status === "unpaid") return;
// Section 5 makes this safe to run more than once.
await recordFulfillment(session);
}
If you only accept cards today, this costs you nothing yet. It starts costing you the day someone enables a bank debit method in the Stripe Dashboard.
5. Events arrive more than once, in any order#
Stripe says it plainly in its webhook docs:
Stripe doesn't guarantee the delivery of events in the order that they're generated.
And in the fulfillment guide, your function "might be called multiple times, possibly concurrently, for the same Checkout Session." Several things cause it:
- Retries. Any non-
2xxor timeout triggers a retry. In live mode, Stripe retries for up to three days with exponential backoff. - Duplicate deliveries. The same event can arrive more than once, and Stripe notes that "in some cases, two separate Event objects are generated and sent" for one change.
- Two events for one purchase. A bank debit sends
completed, thenasync_payment_succeeded. Both reachfulfillCheckout. - Out of order. A retried
completedcan land afterasync_payment_succeeded. Stripe also warns that events "can share a timestamp", so don't sort bycreated.
The fix for ordering is already in section 4: treat every event as a signal to re-read the session, then act on the session's current state. A late completed re-reads a session that's already paid and lands in the duplicate check, which is what fixes the rest.
The usual duplicate check is a read and then a write, and it loses the race:
const existing = await db.findFulfillment(sessionId); // two deliveries at once:
if (existing) return; // both read nothing
await db.createFulfillment(sessionId); // both ship
Let the database decide instead. Key the claim on the Checkout Session ID, not the event ID, because one purchase can produce two different events:
create table fulfillments (
checkout_session_id text primary key,
claimed_at timestamptz not null default now()
);
Then claim and enqueue in one transaction. If anything fails, nothing commits, your route returns a 500, and Stripe's retry gets a clean second attempt:
async function recordFulfillment(session: Stripe.Checkout.Session) {
await db.transaction(async (tx) => {
const claim = await tx.query(
"insert into fulfillments (checkout_session_id) values ($1) on conflict do nothing",
[session.id],
);
if (claim.rowCount === 0) return; // another delivery already has it
await tx.query(
"insert into fulfillment_jobs (checkout_session_id, line_items) values ($1, $2)",
[session.id, JSON.stringify(session.line_items?.data ?? [])],
);
});
}
Inserting the claim and committing it separately from the work is the subtle version of the same bug. If the work fails after the claim commits, every retry sees the claim and skips, and the order never ships.
6. Work out what they bought#
Line items aren't in the event payload. That's why fulfillCheckout retrieves the session with expand: ["line_items"]. For sessions with many lines, Stripe's guide says to page through the line items endpoint instead. Product metadata, payment_intent.succeeded listeners, and the 500-character metadata limit each add a step, worked through in Stripe webhook line items: what did they buy?. Stripe Checkout webhooks: which event to trust covers why listening to both completed and payment_intent.succeeded ships twice.
7. There's no order to fulfill against#
Then comes the part no tutorial covers, because it isn't a Stripe feature. Stripe has Checkout Sessions, PaymentIntents, and Charges. None of them is the record your support team opens, your warehouse picks from, or your accountant reconciles. Stripe has retired an Orders API twice, in 2019 and again in 2022 before its beta reached general availability, so the order layer is yours (the history is here).
So you design one, usually in the hour after the first webhook fires. At minimum it holds the line items as sold, with the price, discount, and tax each line carried; the customer and shipping address; the Checkout Session and PaymentIntent IDs that join it to Stripe; and a status for payment, fulfillment, and refunds. Every later feature inherits that schema.
The problems that arrive in month two all start from it:
- Stock. Nothing decrements inventory. When you add it, two buyers of the last unit both pass. Holding stock at session creation doesn't fix it cleanly either, since a session stays open for 24 hours by default. You end up with holds, releases, and a cleanup job. Stripe inventory management lists the race windows.
- Refunds. Stripe refunds an amount against a PaymentIntent. "Refund the blue shirt" is arithmetic you write: the line's price, its share of the discount, its share of the tax, and what's left on the order. How to refund a line item in Stripe works through it.
- Reconciliation. A payout arrives as one sum. Matching it to orders means walking balance transactions and joining each one back through the IDs you stored.
Vibe coding a store? Don't vibe code the commerce engine follows the same store through discounts, sales tax, disputes, and payouts, with what each step leaves you responsible for.
The production checklist#
If you're shipping on Stripe Checkout, these are the checks that separate the demo from the store:
| Check | What correct looks like |
|---|---|
| Prices | The Server Action accepts IDs and quantities, validates them, and looks up Price IDs |
| Redirect | redirect(session.url), outside any try/catch |
| Success page | Reads the session and shows its status; writes nothing |
| Signature | constructEvent on request.text(), before anything else runs |
| Paid status | Fulfillment checks payment_status; async success and failure are handled |
| Duplicates | A unique constraint on the session ID, claimed in the same transaction as the work |
| Ordering | Every event re-reads the session; nothing depends on arrival order |
| Response time | One durable write, then 2xx; slow work runs in a worker, not in after() |
| Line items | Retrieved with expand, paginated for long carts |
| Order record | Created once, joined to the session and PaymentIntent by ID |
| Tests | Two concurrent deliveries for one session, a bank debit that fails after checkout, a replayed request with an edited price |
The same store on Flint#
Flint is a commerce API where the order exists before the payment, and the payment settles against it. The catalog, the order, its totals and tax, stock holds, refunds by line, and the webhook that says "paid" are all part of the API. Your Next.js app keeps the storefront and calls Flint from the server with @flintpay/node.
The client lives in a server-only module:
// lib/flint.ts
import "server-only";
import { Client } from "@flintpay/node";
export const flint = new Client({
baseUrl: "https://api.withflintpay.com",
apiKey: process.env.FLINT_API_KEY!,
});
Checkout is one Server Action. It creates an order from catalog variant IDs and sends the buyer to that order's hosted checkout:
// app/checkout/actions.ts
"use server";
import { redirect } from "next/navigation";
import { flint } from "@/lib/flint";
export async function checkout(cart: { variantId: string; quantity: number }[]) {
// A catalog line names a variant. Flint copies its name, price, and tax
// settings from the catalog, and rejects a price sent with it.
const order = await flint.orders.create({
line_items: cart.map((item) => ({
type: "variant",
variant_id: item.variantId,
quantity: BigInt(item.quantity),
})),
});
const session = await flint.checkoutSessions.create(
{
type: "order",
order_id: order.order_id,
redirects: {
success_url: `${process.env.APP_URL}/thanks`,
cancel_url: `${process.env.APP_URL}/cart`,
},
},
{ idempotencyKey: `checkout-${order.order_id}` },
);
redirect(session.url!);
}
The browser still chooses which variants and how many, so keep a sane limit on quantities. It can no longer choose what they cost.
This shared-secret verifier requires an endpoint with hmac enabled. New endpoints default to JWT and return no shared secret. Create an HMAC endpoint with this request, then store data.secret as FLINT_WEBHOOK_SECRET:
curl -X POST https://api.withflintpay.com/v1/webhook-endpoints \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: webhook-hmac-001" \
-d '{
"url": "https://example.com/api/flint",
"enabled_events": ["order.paid"],
"signing_methods": ["hmac"]
}'
For an existing endpoint without a secret, issue one and add HMAC, or use JWT verification with Flint's public JWKS.
The webhook route verifies the raw bytes and fulfills from one event, order.paid:
// app/api/flint/route.ts
import { flint } from "@/lib/flint";
import { db } from "@/lib/db";
type FlintEvent = {
event_type: string;
data: { object: { order_id?: string } };
};
export async function POST(request: Request) {
const rawBody = new Uint8Array(await request.arrayBuffer());
let event: FlintEvent;
try {
// Throws on a bad signature or a timestamp more than 5 minutes off.
event = flint.verifyWebhook(rawBody, request.headers, [
process.env.FLINT_WEBHOOK_SECRET!,
]).event as FlintEvent;
} catch {
return new Response("Invalid signature", { status: 400 });
}
if (event.event_type === "order.paid") {
// Delivery is at least once, so the order ID is the claim key.
await db.query(
"insert into fulfillment_jobs (order_id) values ($1) on conflict do nothing",
[event.data.object.order_id],
);
}
return new Response(null, { status: 204 });
}
Here's what happened to each gap:
| Gap | On the tutorial stack | On Flint |
|---|---|---|
| Prices | On the tutorial stackYou build a price lookup | On FlintA catalog line takes its price from the catalog; a caller-supplied price on it returns 400 |
| "Completed" vs paid | On the tutorial stackThree events and a payment_status check | On Flintorder.paid fires only when the order is paid in full, from checkout, a payment link, an invoice, or the API |
| Bank debits | On the tutorial stackYou handle the async events | On FlintHosted checkout tells the buyer the payment is processing and holds the redirect; order.paid waits for the bank |
| What was bought | On the tutorial stackA second API call with expand | On Flintorder.paid carries the order, line items included, as GET /v1/orders/{order_id} returns it |
| Duplicates | On the tutorial stackTwo events per purchase, keyed by session | On FlintEvery retry carries the same webhook-id, and one event type covers every way an order gets paid |
| The order record | On the tutorial stackA schema you design | On FlintThe order exists before checkout, with status fields for payment, fulfillment, and refunds |
| Stock | On the tutorial stackHolds, releases, and a cleanup job | On FlintPaying the order holds stock, commits it on success, and releases it on failure; no stock means no charge |
| Refunds | On the tutorial stackAllocation math you write | On FlintName a line and a quantity; the line's tax comes back with it |
Flint doesn't promise ordering either. Events fan out independently, so the webhooks guide gives the same advice as section 5: treat an event as a signal and read the current resource when order matters. The difference is how much state you have to re-read. On Flint it's one order, with its line items and statuses together.
A refund names the line and quantity instead of an amount, and needs an idempotency key like every route that moves money:
curl -X POST https://api.withflintpay.com/v1/refunds \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Idempotency-Key: refund-ord-1kmn0a-line-1" \
-d '{
"refund_type": "targets",
"order_id": "ord_1kmn0aExample",
"reason": "requested_by_customer",
"line_items": [
{ "order_line_item_id": "li_1kmn0aExample", "quantity": 1,
"tax_refund_mode": "automatic" }
]
}'
Local development doesn't need a tunnel. flint listen --forward-to http://localhost:3000/api/flint streams your sandbox's events to the route with real signatures, and flint listen --print-secret prints the signing secret for .env.local. In a sandbox, success_url accepts http://localhost, and Flint processes cards on Stripe, so Stripe's test card numbers work.
Next.js commerce from a Server Action builds the full storefront: product pages from the catalog, a cart that is an open order in an httpOnly cookie, checkout, and the webhook. Checkout sessions and Webhooks cover the details, and Migrating from Stripe maps Stripe objects to Flint ones.
When the tutorial is enough#
One product, one price, digital delivery, no stock, no partial refunds, card payments only. Then the Checkout Session really is the order, and the code in sections 1 through 5 is the whole job. Ship it.
The gap opens when a second thing becomes true: a catalog, a warehouse, a support team issuing partial refunds, a bank debit option, or a finance team asking which orders are inside Tuesday's payout.
FAQ#
How do I verify a Stripe webhook in the Next.js App Router?#
Read the body with await request.text() in a route.ts POST handler, take the stripe-signature header, and pass both to stripe.webhooks.constructEvent with your whsec_ secret before parsing anything. Route handlers don't parse the body for you, so the Pages Router bodyParser: false config isn't needed.
Why does checkout.session.completed fire with payment_status "unpaid"?#
The buyer finished Checkout with a payment method that settles later, such as ACH Direct Debit. The money hasn't arrived. Wait for checkout.session.async_payment_succeeded before fulfilling, and handle checkout.session.async_payment_failed.
Does Stripe send webhook events in order?#
No. Stripe doesn't guarantee delivery order, and events can share a created timestamp. Treat each event as a prompt to retrieve the current object from the API, and deduplicate with a unique constraint rather than by comparing times.
Should I fulfill orders on the success page or in the webhook?#
The webhook. A buyer can pay and never load the success page, and anyone can open the success URL. Stripe waits up to 10 seconds for your webhook response before redirecting, so the success page can usually just read the session and show its status.
Can I create a Stripe Checkout Session in a Server Action?#
Yes, and it's a good fit. Treat the action as a public endpoint, because Next.js exposes it to direct POST requests. Accept only IDs and quantities, validate them, look up prices on the server, and call redirect(session.url) outside any try/catch.
Do I need a database for Stripe Checkout in Next.js?#
For a single digital product, often not. Once you ship physical goods, track stock, or refund individual items, you need an orders table joined to Stripe by session and PaymentIntent ID. On Flint, the order is part of the API, so the database you keep is for your own app.
Does Flint work with Next.js, and what does it cost?#
Yes. @flintpay/node runs in Server Components, Server Actions, and route handlers, and verifyWebhook takes a route handler's raw bytes and request.headers directly. Card payments cost 3.79% + 35¢ with no monthly fee, and the sandbox is free. Pricing has the full rate card.
Sources#
Everything attributed to Stripe and Next.js above comes from their documentation, checked on 2026-10-24.
- Stripe, Fulfill orders: the six requirements for a fulfillment function, landing pages that aren't guaranteed to load, concurrent calls for one session, delayed payment methods and the async events, the 10-second redirect wait, and
stripe listenredirecting immediately. - Stripe, Receive Stripe events in your webhook endpoint: no guaranteed ordering, shared
createdtimestamps, duplicate and separate Event objects, three days of retries in live mode, the raw body requirement, and returning2xxquickly. - Stripe, Create a Checkout Session: up to 100 line items in payment mode, one discount, and expiry 30 minutes to 24 hours after creation, 24 hours by default.
- Stripe, Remove redirectToCheckout: the 2025-09-30 Stripe.js change.
- Next.js, How to think about data security: Server Actions reachable by direct POST, validating client input,
server-only, and no mutations during rendering. - Next.js, route.js: Web
Requestbodies, webhooks in route handlers, and nobodyParserconfig. - Next.js, after: work scheduled after the response, intended for tasks such as logging and analytics.
