AI SaaS Starter KitAI SaaS Starter KitProduction-ready SaaS boilerplate with Next.js 16, Auth.js, Stripe subscriptions, Prisma, dashboard, teams, admin CMS, and AI-ready API hooks.$29

You fixed Checkout in test mode but Prisma still shows noSubscriptionrow until deploy. Production webhooks need a public URL; locally you needStripe CLI listen forward webhook localhost Next.jsso events hithttp://localhost:3000/api/stripe/webhookwith a valid signature. Without that loop, you cannot trustsubscription syncorplan gatingbefore shipping.

This guide wiresStripe CLI + Next.js App Router: install the CLI,stripe listen --forward-to, paste the CLIwhsec_into.env, run test Checkout orstripe trigger, and verify rows in Prisma using the samerequest.text()pattern fromwebhook signature verification.


What you need running locally

Piece Purposenext devServes/api/stripe/webhookStripe CLIlistenForwards events + signs with temp secret Test mode API keyssk_test_...in.envCLI webhook secretwhsec_...from listen output (not Dashboard prod secret)

Stripe Dashboard endpoint secrets apply to deployed URLs only. Local forwarding uses adifferentsigning secret printed by the CLI.

Prerequisites

  • Webhook Route Handler (articles 01 and 02).

  • Stripe test mode enabled.

  • Middleware excludes/api/stripe/webhook(seeAuth.js middleware).


Step 1: Install Stripe CLI

macOS (Homebrew):

brew install stripe/stripe-cli/stripe

Windows (Scoop):

scoop install stripe

Linux:download fromStripe CLI docsor use package manager builds.

Verify:

stripe --version

Step 2: Log in and forward to Next.js

stripe login

Approve the browser prompt. Then forward to your webhook path (match your repo):

stripe listen --forward-to localhost:3000/api/stripe/webhook

The CLI prints something like:

Ready! Your webhook signing secret is whsec_xxxxxxxxxxxx

Copy that value into.env.local:

STRIPE_WEBHOOK_SECRET=whsec_xxxxxxxxxxxx
STRIPE_SECRET_KEY=sk_test_...

Restartnext devafter changing env vars.

stripe cli listen forward webhook localhost next.jsis the exact workflow developers search when Dashboard endpoints cannot reachlocalhost.


Step 3: Run Next.js and confirm the route

npm run dev

In another terminal, keepstripe listenrunning. Optional health check: trigger a test event (Step 4) and watch both terminals.

Your handler should:

  1. await request.text()

  2. stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET)

  3. Handlecheckout.session.completed,customer.subscription.updated, etc.

Minimal handler skeleton for smoke testing with CLI:

export async function POST(request: Request) {
  const body = await request.text();
  const signature = (await headers()).get("stripe-signature");
  if (!signature) return NextResponse.json({ error: "No signature" }, { status: 400 });

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
  }

  console.log("Verified", event.type);
  return NextResponse.json({ received: true });
}

Oncestripe trigger payment_intent.succeededreturns 200, swap in your real switch statement from article 01.

If verification fails, fix signatures before debugging business logic (article 02).

Parallel terminals:typical layout is three windows:next dev,stripe listen, and a shell forstripe triggeror browser Checkout. Keeping listen running across handler edits is fine; restart listen only when you suspect a stalewhsec_.


Step 4: Trigger events without full Checkout

Synthetic events:

stripe trigger checkout.session.completed
stripe trigger customer.subscription.updated
stripe trigger customer.subscription.deleted

Useful when iterating on switch cases. Synthetic payloads may omit metadata your handler expects (for exampleuserId). Prefer real test Checkout when testingcheckout.session.completedupserts.

Real Checkout flow:

  1. Start listen + dev server.

  2. Complete test Checkout with card4242 4242 4242 4242.

  3. CLI shows forwarded events; Prisma Studio shows newSubscriptionrow.


Step 5: Match CLI secret to environment only on local

EnvironmentSTRIPE_WEBHOOK_SECRETsource Local + CLI listenwhsec_from CLI output Vercel production Dashboard endpoint signing secret Stripe CLI + staging tunnel CLI secret for that listen session

Using the Dashboard production secret with CLI-forwarded bodies causesInvalid signature. Using the CLI secret in production causes the same.

Rotate CLI secret each time you restartstripe listen(new session).


Step 6: Middleware and auth must not block webhooks

Stripe POSTs do not send your session cookie. Ifmiddlewarematches/api/stripe/webhook, you may see redirects or empty bodies before your handler runs.

Exclude the path inmiddleware.tsmatcher negative lookahead or narrow matcher list.

Symptom: CLI shows200but handler never logs, or signature fails because something else read the body.


Step 7: Debugging checklist

When something fails, work in order: (1) does CLI show a forward attempt, (2) what HTTP status did Next return, (3) do server logs showVerified event.type, (4) did Prisma change. Skipping step 2 and rewriting handler logic is how teams burn hours on unrelated bugs.

CLI shows 400 from your app

  • WrongSTRIPE_WEBHOOK_SECRET(Dashboard vs CLI mix-up).

  • Handler calledrequest.json()beforeconstructEvent.

  • Typo in forward URL (/api/stripe/webhooksvs/api/stripe/webhook).

CLI shows connection refused

  • next devnot running.

  • Wrong port (3000 vs 3001).

Events arrive but Prisma empty

  • Handler throws after verification (check server logs).

  • Missingmetadata.userIdon Checkout session.

  • Wrong test vs live key on customer id.

No events after Checkout

  • Listen not running.

  • Checkout used live keys while listen uses test account (stay in test mode).

Works locally, fails on Vercel

  • Production needs Dashboard webhook URL + productionwhsec_.

  • Do not copy CLI secret to Vercel.


Step 8: Inspect forwarded events in the CLI

Whilestripe listenruns, the terminal prints event types and response codes from your app. Add a single log line after verification:

console.log("[stripe]", event.type, event.id);

Strip verbose logging before production. For noisy dev sessions, filter CLI output or redirect to a file.

stripe logs tail(account activity) complements webhooks when debugging Checkout redirects:

stripe logs tail

Use it when the CLI shows no forward but the browser completed Checkout (client error vs server error).


Step 8b:.env.localtemplate for new developers

Document in README:

STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_from_stripe_listen_not_dashboard
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
DATABASE_URL=postgresql://...

Comment thatSTRIPE_WEBHOOK_SECRETmust be refreshed when restarting listen. Onboarding friction drops when the team knows not to paste Dashboard production secrets into local env.


Step 8c: ngrok or cloud tunnels (optional)

Some teams registerhttps://abc.ngrok.io/api/stripe/webhookin the Dashboard and skip CLI forwarding. That works for demos but is slower for daily dev. CLI remains the default forstripe cli listen forward webhook localhost next.jsbecause it requires no public URL and rotates signing automatically per session.

If you use ngrok, the Dashboard endpoint signing secret applies, not the CLI secret. Pick one workflow per developer machine to avoid secret confusion.


Step 9: Replay and resend after fixing handler

Stripe Dashboard:Developers → Webhooks → select event → Resend (works for cloud endpoints).

Local:re-runstripe trigger ...or repeat Checkout. For idempotent handlers, storeevent.id(article 09 in this series:idempotent webhooks).


Step 10: End-to-end local test matrix

  1. Startstripe listenandnext devwith CLIwhsec_in env.

  2. Register/login test user (Auth.js).

  3. Complete Checkout for Pro plan.

  4. Confirmcheckout.session.completedin CLI output.

  5. Prisma:SubscriptionrowACTIVEfor user.

  6. Open/dashboard/analytics(or Pro route):plan gatingallows access.

  7. stripe trigger customer.subscription.deleted(or cancel in portal against test customer): gate denies Pro after handler runs.

Document which events your handler supports (article 01 minimum set).

Prisma Studio:after Checkout, refreshSubscriptionandUsertables. IfstripeCustomerIdis set but subscription is missing, your handler never reached the upsert branch. CLI logs plus serverconsole.lognarrow that quickly.

404 on webhook route:confirm the file isapp/api/stripe/webhook/route.ts(singularwebhook) and that you did not mount under a route group that shifts the path.


Step 11: Windows and WSL notes

On Windows, run CLI and Next in the same network context. WSL users forward tolocalhost:3000from WSL when Next runs inside WSL; if Next runs on Windows host, use the host IP documented for your setup.

Firewall prompts blockingstripeare common on first run. Allow private network for the CLI.

CI note:unit tests usually mockconstructEventrather than running CLI in GitHub Actions. CLI listen is a developer-machine workflow; production confidence comes from integration tests against fixture payloads plus Dashboard staging endpoints.

Port conflicts:if port 3000 is taken, runnext dev -p 3001and forwardlocalhost:3001/api/stripe/webhook. Update listen URL to match.


Common failures

Listening on wrong path

Your kit uses/api/stripe/webhook. Forward URL must match exactly.

Multiple listen processes

Two CLI sessions print two secrets. Only one matches your.env. Kill extra listen terminals.

Test clock and CLI

Advanced billing tests may use test clocks; triggers still forward the same way.

Edge runtime on webhook route

Stripe Node SDK expectsruntime = "nodejs"on the webhook route (article 02).

Customer Portal cancel during local dev

After portal cancel, wait forcustomer.subscription.updatedin CLI output. Then refresh a gated page. If UI is stale for one request, webhooks may still be in flight; avoid gating on client-only success params (article 07).

Team workflow with two developers

Each developer runs their ownstripe listenand uses their own CLIwhsec_in local.env.local. Do not commit webhook secrets. Share event handler code, not env files.


Webhook-ready local dev in the kit

CLI forwarding, raw body verification, subscription upserts, and plan gates are the loop every SaaS team repeats.

Skryptix AI SaaS Starter Kitincludes:

  • /api/stripe/webhookwith signature verification

  • Prisma subscription sync and plan gating

  • Checkout, Customer Portal, and Auth.js middleware

  • Docs for Stripe test mode and deploy

Clone a repo where/api/stripe/webhookalready works.AI SaaS Starter KitonSkryptix.

AI SaaS Starter KitAI SaaS Starter KitProduction-ready SaaS boilerplate with Next.js 16, Auth.js, Stripe subscriptions, Prisma, dashboard, teams, admin CMS, and AI-ready API hooks.$29



FAQ

How do I forward Stripe webhooks to localhost in Next.js?

Runstripe listen --forward-to localhost:3000/api/stripe/webhook, copy the CLI signing secret toSTRIPE_WEBHOOK_SECRET, and verify events withstripe.webhooks.constructEventonrequest.text()in your Route Handler.

What is the difference between CLI whsec and Dashboard whsec?

The CLI prints a temporary signing secret for forwarded events. The Dashboard provides a secret per registered endpoint URL. Use CLI secret only during local listen.

Can I test webhooks without Stripe CLI?

You can POST fixtures with tools like ngrok + Dashboard endpoints, but CLI is the standard local path. CLI also signs payloads correctly forconstructEvent.

Which stripe trigger events should I use first?

Start withcheckout.session.completed,customer.subscription.updated, andcustomer.subscription.deletedto match a typical SaaS webhook handler.

Why does middleware break local webhook tests?

Auth middleware may redirect unauthenticated requests before the webhook handler reads the body. Exclude/api/stripe/webhookfrom the matcher.

Does Stripe CLI work with Next.js Turbopack?

Yes. The webhook route is standard App Router; CLI forwards HTTP to your port regardless of bundler. Keepruntime = "nodejs"on the handler.

How often should I restart stripe listen?

Restart when the CLI prints a new signing secret or afterstripe loginchanges accounts. Mismatchedwhsec_causes signature errors until.env.localmatches.

What path should stripe listen use for this kit?

Use/api/stripe/webhookon the same port asnext dev(default 3000). The forward URL path must match your Route Handler file layout exactly. If you rename the route, update both listen and Dashboard staging endpoints.


Written by the team behind Skryptix. We build the AI SaaS Starter Kit so founders can focus on product, not auth and billing infrastructure.