# Prompt to Add Stripe Checkout to a Next.js App

> AI agent prompt to add Stripe Checkout with webhook handling, customer portal, and subscription status to a Next.js App Router project.

**Type:** Prompt  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Next.js, PostgreSQL, TypeScript  
**Difficulty:** hard  
**Updated:** 2026-06-08

---

Give this prompt to your agent to implement the complete Stripe billing flow — checkout
session creation, webhook processing, customer portal, and subscription status gating —
with proper webhook signature verification and no secrets in client code.

## Main Prompt

```txt title="Main Prompt"
You are working in a Next.js 15 App Router project with TypeScript and PostgreSQL.
Auth is already set up with a `getSession()` helper. The pricing page already defines
`PLANS` with Stripe Price IDs.

Task: wire up Stripe Checkout for subscription billing.

Requirements:
- Install `stripe` (server-only) and `@stripe/stripe-js` (client). Do NOT import `stripe` in
  Client Components or expose `STRIPE_SECRET_KEY` to the browser.
- Create `src/lib/stripe.ts`: export a singleton Stripe client using `STRIPE_SECRET_KEY`.
- Create a Server Action `src/lib/actions/create-checkout.ts`:
  - Get the current user session; return an error if not authenticated.
  - Create a Stripe Checkout Session in `subscription` mode.
  - Set `success_url` to `/dashboard?session_id={CHECKOUT_SESSION_ID}`.
  - Set `cancel_url` to `/pricing`.
  - Store the Stripe `customerId` in the `users` table (`stripe_customer_id` column).
  - Return the Checkout Session URL.
- Create `src/app/api/stripe/webhook/route.ts`:
  - Read the raw body using `request.text()`.
  - Verify the signature using `stripe.webhooks.constructEvent(body, sig, STRIPE_WEBHOOK_SECRET)`.
  - Handle events: `checkout.session.completed`, `customer.subscription.updated`,
    `customer.subscription.deleted`.
  - On each event, update the `users` table: set `subscription_status` and `subscription_tier`.
  - Return `{ received: true }` with status 200.
  - On signature failure, return 400.
- Create `src/lib/actions/create-portal.ts`: create a Stripe Customer Portal session and return the URL.
- Add a PostgreSQL migration `migrations/0011_add_stripe_columns.sql` adding
  `stripe_customer_id TEXT`, `subscription_status TEXT`, `subscription_tier TEXT` to `users`.
- Add all Stripe keys to `.env.example`: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`,
  `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.
- Do NOT use the deprecated `stripe.charges` API. Use Payment Intents / Checkout Sessions only.

Stop and list all planned file changes before writing any code.
```

## Implementation Notes

- Webhook signature verification requires the **raw** request body — if you parse it as JSON first,
  the signature check will fail. Use `request.text()` not `request.json()`.
- The webhook handler must be excluded from Next.js body size limits via a route config:
  `export const config = { api: { bodyParser: false } }` (Pages Router) — in App Router, use
  `export const dynamic = 'force-dynamic'` and read the stream directly.
- Test webhooks locally with the Stripe CLI: `stripe listen --forward-to localhost:3000/api/stripe/webhook`.
- Store `stripe_customer_id` on first checkout to avoid creating duplicate Stripe customers.

## Expected File Changes

```txt
src/lib/stripe.ts                           (new)
src/lib/actions/create-checkout.ts          (new — Server Action)
src/lib/actions/create-portal.ts            (new — Server Action)
src/app/api/stripe/webhook/route.ts         (new — Route Handler)
migrations/0011_add_stripe_columns.sql      (new)
.env.example                                (edited)
package.json                                (edited)
```

## Acceptance Criteria

- Clicking a pricing CTA redirects to Stripe Checkout for the correct plan.
- Completing a test checkout updates `subscription_status = 'active'` in PostgreSQL.
- The Stripe Customer Portal link redirects to the Stripe-hosted portal.
- Sending a test `customer.subscription.deleted` event via Stripe CLI sets `subscription_status = 'canceled'`.
- A webhook with an invalid signature returns HTTP 400.

## Test Commands

```bash
bun add stripe @stripe/stripe-js
psql "$DATABASE_URL" -f migrations/0011_add_stripe_columns.sql
bun run typecheck
bun run dev &
stripe listen --forward-to localhost:3000/api/stripe/webhook
stripe trigger checkout.session.completed
# verify users table updated
psql "$DATABASE_URL" -c "SELECT stripe_customer_id, subscription_status FROM users LIMIT 5;"
```

## Common AI Mistakes

- Importing `stripe` (server SDK) in a Client Component, exposing `STRIPE_SECRET_KEY`.
- Parsing the webhook body as JSON before signature verification, causing all webhook validations to fail.
- Creating a new Stripe customer on every checkout instead of reusing `stripe_customer_id`.
- Using `stripe.charges.create` (deprecated) instead of `stripe.checkout.sessions.create`.

## Fix Prompt

```txt title="Fix Prompt"
Webhook signature verification fails with `No signatures found matching the expected signature`.
Fix in order:
1. In the webhook route, replace `await request.json()` with `const body = await request.text()`.
2. Ensure `stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!)` receives
   the raw string body, not a parsed object.
3. Add `export const dynamic = 'force-dynamic'` at the top of the route file.
Show only the corrected route handler diff.
```