PAYMENTSNEXT.JS 16STRIPE

Take payments in Next.js with Stripe: Checkout, webhooks and orders that can’t be faked

Sell a product from a Next.js 16 app with Stripe Checkout, record every order exactly once from a verified webhook, and only hand over what was bought when Stripe says it’s paid. Every step was run on a fresh project, with a real test payment, before this was published.

Ali Murtaza · 12 min read ·

Tested step by step on with Next.js 16.4.6, Stripe 23.2.0 and Prisma 7.10.1

By the end of this guide your app sells something: a Buy button that opens Stripe’s payment page, a success page, and a download that only works for someone who really paid. More importantly, you’ll build the three things most payment tutorials skip: checking that a webhook really came from Stripe, recording each order once even when Stripe sends the same event twice, and never trusting the browser’s word that a payment happened.

Every file is shown in full. The guide was run from start to finish on a fresh create-next-app project and a fresh shadcn init project, with Next.js 16.4, the stripe package 23, Prisma 7.10 and Stripe’s test mode, including a real test payment with Stripe’s test card.

Before you start

  • A Next.js 16 app with Prisma and Postgres. Do steps 1 to 6 of Next.js 16 + Prisma 7 + Postgres on a fresh project first. This guide adds to exactly that setup.
  • A free Stripe account. You’ll stay in test mode (Stripe calls a test account a sandbox): no real money moves, ever.
  • The Stripe CLI. On a Mac, brew install stripe/stripe-cli/stripe; for Windows and Linux, follow Stripe’s install page. Check with stripe --version.

1. Install Stripe’s package and sign the CLI in

Terminalbash
npm install stripestripe login

stripe login opens your browser to connect the CLI to your account. Choose your sandbox (test mode) and allow access. The CLI can then create products and forward webhooks to your computer.

2. Create the product and its price

Terminalbash
stripe prices create --unit-amount 2900 --currency usd -d "product_data[name]=The Next.js Field Guide"

This creates a product and its $29.00 price in one go (unit-amount is in cents). The command prints the new price as JSON; the first line that matters is "id": "price_…". Copy that id. (You can also do this in the Dashboard under Product catalog → Add product: open the product and copy the price’s id.)

3. Add your Stripe settings

Get the webhook signing secret your CLI will use (you’ll start it in step 11):

Terminalbash
stripe listen --print-secret

It prints one line starting with whsec_. Now add four lines to the end of .env, replacing the three values in capitals:

.env (add at the end)env
# Stripe Dashboard → Developers → API keys → Secret key (starts sk_test_)STRIPE_SECRET_KEY="PASTE_YOUR_SECRET_KEY"# The price id from step 2 (starts price_)STRIPE_PRICE_ID="PASTE_YOUR_PRICE_ID"# From stripe listen --print-secret (starts whsec_)STRIPE_WEBHOOK_SECRET="PASTE_YOUR_WEBHOOK_SECRET"# Where your app runsAPP_URL="http://localhost:3000"
The secret key can take money and refund it. Keep it in .env (already ignored by Git) and never in a file a browser loads: no NEXT_PUBLIC_ prefix, ever.

4. Add an orders table

Replace prisma/schema.prisma with this. It keeps your Task model and adds an Order model. stripeSessionId is @unique: that one word is what will stop a payment being recorded twice.

prisma/schema.prismaprisma
generator client { provider = "prisma-client" output = "../generated/prisma"}datasource db { provider = "postgresql"}model Task { id Int @id @default(autoincrement()) title String done Boolean @default(false) createdAt DateTime @default(now())}model Order { id Int @id @default(autoincrement()) stripeSessionId String @unique email String amountTotal Int currency String createdAt DateTime @default(now())}
Terminalbash
npx prisma migrate dev --name add-ordersnpx prisma generate

As in the Prisma guide: the first ends with “Your database is now in sync with your schema.”, the second with “Generated Prisma Client”.

5. Create the Stripe client

lib/stripe.tsts
import Stripe from "stripe";export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

Only server code imports this file: server actions, route handlers and server components. That keeps the secret key on the server.

6. Record an order — once

Two different places will record the same payment: the webhook (step 8) and the success page (step 9). Stripe may also send the same webhook more than once. So the code that records an order has to be safe to run any number of times:

lib/orders.tsts
import type Stripe from "stripe";import { prisma } from "@/lib/prisma";/** * Records a paid Checkout session as an order — once, however many times * it's called. The webhook and the success page both call it, and Stripe * may deliver the same webhook more than once. */export async function recordOrder(session: Stripe.Checkout.Session) { if (session.payment_status !== "paid") return null; return prisma.order.upsert({ where: { stripeSessionId: session.id }, create: { stripeSessionId: session.id, email: session.customer_details?.email ?? "", amountTotal: session.amount_total ?? 0, currency: session.currency ?? "usd", }, update: {}, });}
  • payment_status !== "paid": a session can complete without being paid yet (bank payments take days). Those wait for the async_payment_succeeded event.
  • upsert with an empty update: the first call creates the row; every later call finds it and changes nothing. Because stripeSessionId is unique, Postgres itself refuses a second row even if two calls arrive at the same moment.

7. Start the checkout

A server action creates a Checkout session and sends the browser to Stripe’s payment page. Create the folder app/buy and these two files in it:

app/buy/actions.tsts
"use server";import { redirect } from "next/navigation";import { stripe } from "@/lib/stripe";export async function startCheckout() { const session = await stripe.checkout.sessions.create({ mode: "payment", line_items: [{ price: process.env.STRIPE_PRICE_ID!, quantity: 1 }], success_url: `${process.env.APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${process.env.APP_URL}/buy`, }); redirect(session.url!);}
app/buy/page.tsxtsx
import { startCheckout } from "./actions";export default function BuyPage() { return ( <main className="mx-auto max-w-xl p-8"> <h1 className="text-2xl font-semibold">The Next.js Field Guide</h1> <p className="mt-2">A downloadable guide. One payment, yours to keep.</p> <form action={startCheckout} className="mt-6"> <button type="submit" className="rounded bg-black px-4 py-2 text-white"> Buy for $29 </button> </form> </main> );}
  • The price comes from your Stripe price id on the server, never from the page: nobody can change what they pay by editing the HTML.
  • {CHECKOUT_SESSION_ID} is written exactly like that. Stripe swaps in the real session id when it sends the buyer back.
  • redirect() works from a server action, even to another site like checkout.stripe.com.

8. Receive Stripe’s webhook

When a payment succeeds, Stripe sends a request to your server: a webhook. It’s the one message you can trust, because it carries a signature only Stripe can make. Create the folders app/api/webhooks/stripe and this file:

app/api/webhooks/stripe/route.tsts
import type Stripe from "stripe";import { stripe } from "@/lib/stripe";import { recordOrder } from "@/lib/orders";export async function POST(request: Request) { // The signature is computed over the exact bytes Stripe sent, so read the // body as text — never parse it first. const body = await request.text(); 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 }); } if ( event.type === "checkout.session.completed" || event.type === "checkout.session.async_payment_succeeded" ) { await recordOrder(event.data.object); } return Response.json({ received: true });}
  • constructEvent checks the signature and the timestamp. A request that didn’t come from Stripe, or came long ago, never gets past it — and nothing is recorded.
  • If your route answers with anything other than a 2xx status, Stripe tries again later (for up to three days in live mode). Answer 200 once you’ve handled it, and keep the work quick.

9. Show the receipt — after asking Stripe

The buyer comes back to /success?session_id=cs_test_…. Anyone can type that address, so the page asks Stripe whether that session is really paid before it says “thank you”:

app/success/page.tsxtsx
import { Suspense } from "react";import { connection } from "next/server";import { stripe } from "@/lib/stripe";import { recordOrder } from "@/lib/orders";export default function SuccessPage({ searchParams,}: { searchParams: Promise<{ session_id?: string }>;}) { return ( <main className="mx-auto max-w-xl p-8"> <Suspense fallback={<p>Checking your payment…</p>}> <Receipt searchParams={searchParams} /> </Suspense> </main> );}async function Receipt({ searchParams,}: { searchParams: Promise<{ session_id?: string }>;}) { await connection(); const { session_id } = await searchParams; if (!session_id?.startsWith("cs_")) return <p>We couldn’t find that order.</p>; // Ask Stripe, don't trust the URL: anyone can type /success?session_id=… const session = await stripe.checkout.sessions .retrieve(session_id) .catch(() => null); if (!session) return <p>We couldn’t find that order.</p>; if (session.payment_status !== "paid") { return <p>This order hasn’t been paid yet. If you’ve just paid, refresh in a minute.</p>; } await recordOrder(session); return ( <> <h1 className="text-2xl font-semibold">Thank you!</h1> <p className="mt-2"> A receipt is on its way to {session.customer_details?.email}. </p> {/* A plain <a>, not <Link>: this is a file, not a page to prefetch. */} <a href={`/download?session_id=${session.id}`} className="mt-6 inline-block rounded bg-black px-4 py-2 text-white" > Download the guide </a> </> );}

It calls recordOrder too, so the order exists even if the webhook is late or missed — and thanks to step 6 that never makes a second one. <Suspense> and connection() are the same pattern as the Prisma guide’s task list: this part needs a real request.

10. Hand over what was bought

The download only answers for an order that’s in your database — which only a verified payment can put there. Create app/download/route.ts:

app/download/route.tsts
import { prisma } from "@/lib/prisma";export async function GET(request: Request) { const sessionId = new URL(request.url).searchParams.get("session_id") ?? ""; const order = await prisma.order.findUnique({ where: { stripeSessionId: sessionId }, }); if (!order) return new Response("No paid order for that link.", { status: 404 }); return new Response("The Next.js Field Guide\n\nThanks for buying!\n", { headers: { "Content-Type": "text/plain; charset=utf-8", "Content-Disposition": 'attachment; filename="nextjs-field-guide.txt"', }, });}

In a real shop this would stream a file from storage or open a course; the check in front of it is the part that matters.

11. Make a test purchase

You need two terminals. In the first, start your app:

Terminalbash
npm run dev

In the second, forward Stripe’s webhooks to it:

Terminalbash
stripe listen --forward-to localhost:3000/api/webhooks/stripe

It prints “Ready!” and the same whsec_ secret as in step 3. Leave it running. Then open http://localhost:3000/buy, click Buy for $29, and pay with Stripe’s test card:

  • Email: any address. Card number: 4242 4242 4242 4242.
  • Expiry: any future date, like 12 / 34. Security code: any three digits. Name: anything.
  • If Stripe offers your local currency next to $29.00, either is fine: it’s Stripe’s Adaptive Pricing, and the order records whichever you pay in.

You land on “Thank you!” with a Download the guide button. In the second terminal you’ll see checkout.session.completed followed by [200] POST http://localhost:3000/api/webhooks/stripe. Run npx prisma studio and open Order: there’s one row, with your email and the amount in cents (2900 if you paid in dollars).

12. Prove it can’t be faked

Keep both terminals running and try to break it from a third:

Terminalbash
curl -i -X POST http://localhost:3000/api/webhooks/stripe -d '{"type":"checkout.session.completed"}'

A forged webhook: the answer is HTTP/1.1 400 Bad Request and “Invalid signature”, and no order appears. Now replay a real event. In the stripe listen terminal, copy the id after checkout.session.completed (it starts evt_) and send it again:

Terminalbash
stripe events resend PASTE_THE_EVENT_ID

Stripe delivers it a second time (the listen terminal shows another [200]), and Order still has one row. Finally, open http://localhost:3000/success?session_id=cs_test_madeup: “We couldn’t find that order.” And if you start a checkout and close Stripe’s page without paying, that session’s /download link answers “No paid order for that link.”

13. Go live

  • Deploy as in the Prisma guide (step 13), and add STRIPE_SECRET_KEY, STRIPE_PRICE_ID and APP_URL (your real address, like https://your-app.vercel.app) to the Vercel project’s environment variables.
  • stripe listen only forwards to your computer. For the deployed app, open Stripe’s Dashboard → Developers → Webhooks → Add destination. Choose the events checkout.session.completed and checkout.session.async_payment_succeeded, and set the URL to https://your-app.vercel.app/api/webhooks/stripe.
  • That destination has its own signing secret (also whsec_…). Put it in Vercel as STRIPE_WEBHOOK_SECRET and redeploy.
  • To take real money: activate your Stripe account, switch the Dashboard out of test mode, create the price again there, and use the live secret key, price id and webhook secret. Nothing in the code changes.

If something goes wrong

  • “Neither apiKey nor config.authenticator provided”. STRIPE_SECRET_KEY isn’t set. Check .env, then stop and restart npm run dev (it reads .env when it starts).
  • “No such price: 'price_…'”. The price id is mistyped, or it belongs to another account or to live mode. Copy it again from step 2’s output.
  • stripe listen shows [400] for every event. The signature check is failing: STRIPE_WEBHOOK_SECRET doesn’t match what stripe listen --print-secret prints (restart npm run dev after changing it). In your own code, the classic cause is parsing the body before checking it: Stripe’s message is “No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?”
  • You paid but no Order row appeared, and stripe listen wasn’t running. Open the success page’s address again: it records the order itself. In production, check the destination’s deliveries in Stripe’s Dashboard (Developers → Webhooks).
  • The success page says the order hasn’t been paid. The checkout was closed before paying, or the payment method takes time (bank debits). The async_payment_succeeded webhook records it when it clears.

Questions people ask

Do I still need a webhook if I have a success page?

Yes. Some payments only finish later (bank payments can take days), and a buyer can close the tab before the success page ever loads. The webhook is Stripe telling your server directly, signed so nobody else can fake it. Here both record the order, and the unique session id makes sure it’s only recorded once.

How do I stop one payment being recorded twice?

Make the Checkout session id @unique on your orders table, and record orders with an upsert whose update is empty. Stripe can send the same event more than once, and the success page records the order too. The first call creates the row; every call after that finds it and changes nothing.

Can someone change the price in their browser?

Not with this setup. The price comes from your Stripe price id, which is read on the server when the Checkout session is created. The page only says “I want to buy this”, so editing the HTML or the request does nothing to what Stripe charges.

Which card do I use to test Stripe Checkout?

4242 4242 4242 4242, with any future expiry date, any three-digit security code and any name. It only works in test mode (a sandbox, in Stripe’s words), where no real money ever moves.

Where to go next

  • Tie purchases to accounts: with Better Auth, pass the signed-in user’s id as client_reference_id when creating the session, save it on the order, and show “Your purchases” from the database.
  • Handle refunds: listen for charge.refunded the same verified way and mark the order refunded, so the download stops answering.
  • Read Stripe’s Checkout fulfilment guide for subscriptions and more payment methods.
Found this useful? Give it a heart, or share it with someone who’d use it.
WRITTEN BY
Ali Murtaza

I build SaaS products with Next.js and teach them start to finish, in full courses here and free builds on YouTube.

KEEP READING
FREE BUILDS ON THIS STACK