{
  "id": "add-stripe-checkout-to-nextjs",
  "type": "prompts",
  "category": "prompts",
  "locale": "en",
  "url": "/prompts/add-stripe-checkout-to-nextjs",
  "title": "Prompt to Add Stripe Checkout to a Next.js App",
  "description": "AI agent prompt to add Stripe Checkout with webhook handling, customer portal, and subscription status to a Next.js App Router project.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "PostgreSQL",
    "TypeScript"
  ],
  "tags": [
    "nextjs",
    "typescript",
    "postgres",
    "auth",
    "security"
  ],
  "difficulty": "hard",
  "updated": "2026-06-08",
  "markdown": "Give this prompt to your agent to implement the complete Stripe billing flow — checkout\nsession creation, webhook processing, customer portal, and subscription status gating —\nwith proper webhook signature verification and no secrets in client code.\n\n## Main Prompt\n\n```txt title=\"Main Prompt\"\nYou are working in a Next.js 15 App Router project with TypeScript and PostgreSQL.\nAuth is already set up with a `getSession()` helper. The pricing page already defines\n`PLANS` with Stripe Price IDs.\n\nTask: wire up Stripe Checkout for subscription billing.\n\nRequirements:\n- Install `stripe` (server-only) and `@stripe/stripe-js` (client). Do NOT import `stripe` in\n  Client Components or expose `STRIPE_SECRET_KEY` to the browser.\n- Create `src/lib/stripe.ts`: export a singleton Stripe client using `STRIPE_SECRET_KEY`.\n- Create a Server Action `src/lib/actions/create-checkout.ts`:\n  - Get the current user session; return an error if not authenticated.\n  - Create a Stripe Checkout Session in `subscription` mode.\n  - Set `success_url` to `/dashboard?session_id={CHECKOUT_SESSION_ID}`.\n  - Set `cancel_url` to `/pricing`.\n  - Store the Stripe `customerId` in the `users` table (`stripe_customer_id` column).\n  - Return the Checkout Session URL.\n- Create `src/app/api/stripe/webhook/route.ts`:\n  - Read the raw body using `request.text()`.\n  - Verify the signature using `stripe.webhooks.constructEvent(body, sig, STRIPE_WEBHOOK_SECRET)`.\n  - Handle events: `checkout.session.completed`, `customer.subscription.updated`,\n    `customer.subscription.deleted`.\n  - On each event, update the `users` table: set `subscription_status` and `subscription_tier`.\n  - Return `{ received: true }` with status 200.\n  - On signature failure, return 400.\n- Create `src/lib/actions/create-portal.ts`: create a Stripe Customer Portal session and return the URL.\n- Add a PostgreSQL migration `migrations/0011_add_stripe_columns.sql` adding\n  `stripe_customer_id TEXT`, `subscription_status TEXT`, `subscription_tier TEXT` to `users`.\n- Add all Stripe keys to `.env.example`: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`,\n  `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY`.\n- Do NOT use the deprecated `stripe.charges` API. Use Payment Intents / Checkout Sessions only.\n\nStop and list all planned file changes before writing any code.\n```\n\n## Implementation Notes\n\n- Webhook signature verification requires the **raw** request body — if you parse it as JSON first,\n  the signature check will fail. Use `request.text()` not `request.json()`.\n- The webhook handler must be excluded from Next.js body size limits via a route config:\n  `export const config = { api: { bodyParser: false } }` (Pages Router) — in App Router, use\n  `export const dynamic = 'force-dynamic'` and read the stream directly.\n- Test webhooks locally with the Stripe CLI: `stripe listen --forward-to localhost:3000/api/stripe/webhook`.\n- Store `stripe_customer_id` on first checkout to avoid creating duplicate Stripe customers.\n\n## Expected File Changes\n\n```txt\nsrc/lib/stripe.ts                           (new)\nsrc/lib/actions/create-checkout.ts          (new — Server Action)\nsrc/lib/actions/create-portal.ts            (new — Server Action)\nsrc/app/api/stripe/webhook/route.ts         (new — Route Handler)\nmigrations/0011_add_stripe_columns.sql      (new)\n.env.example                                (edited)\npackage.json                                (edited)\n```\n\n## Acceptance Criteria\n\n- Clicking a pricing CTA redirects to Stripe Checkout for the correct plan.\n- Completing a test checkout updates `subscription_status = 'active'` in PostgreSQL.\n- The Stripe Customer Portal link redirects to the Stripe-hosted portal.\n- Sending a test `customer.subscription.deleted` event via Stripe CLI sets `subscription_status = 'canceled'`.\n- A webhook with an invalid signature returns HTTP 400.\n\n## Test Commands\n\n```bash\nbun add stripe @stripe/stripe-js\npsql \"$DATABASE_URL\" -f migrations/0011_add_stripe_columns.sql\nbun run typecheck\nbun run dev &\nstripe listen --forward-to localhost:3000/api/stripe/webhook\nstripe trigger checkout.session.completed\n# verify users table updated\npsql \"$DATABASE_URL\" -c \"SELECT stripe_customer_id, subscription_status FROM users LIMIT 5;\"\n```\n\n## Common AI Mistakes\n\n- Importing `stripe` (server SDK) in a Client Component, exposing `STRIPE_SECRET_KEY`.\n- Parsing the webhook body as JSON before signature verification, causing all webhook validations to fail.\n- Creating a new Stripe customer on every checkout instead of reusing `stripe_customer_id`.\n- Using `stripe.charges.create` (deprecated) instead of `stripe.checkout.sessions.create`.\n\n## Fix Prompt\n\n```txt title=\"Fix Prompt\"\nWebhook signature verification fails with `No signatures found matching the expected signature`.\nFix in order:\n1. In the webhook route, replace `await request.json()` with `const body = await request.text()`.\n2. Ensure `stripe.webhooks.constructEvent(body, sig, process.env.STRIPE_WEBHOOK_SECRET!)` receives\n   the raw string body, not a parsed object.\n3. Add `export const dynamic = 'force-dynamic'` at the top of the route file.\nShow only the corrected route handler diff.\n```"
}