Set up production-ready auth in minutes. Supports Better Auth and Firebase Auth with OAuth social login, UI components, database schemas. Auto-detects existing themes.

version
1.7.1
GitHub stars
9

Install

/plugin install shipwithai-auth@shipwithai

Run it inside Claude Code after adding the marketplace with /plugin marketplace add ShipWithAI/shipwithai-plugins.

Contents

Discovered from source

Skills 2

Auth Doctor — Diagnostic Guide

Health check for existing authentication setups. Detects misconfigurations, missing files, security issues, and dangerous code patterns across Better Auth and Firebase Auth projects.

When to Use

  • After running /shipwithai-auth:setup — final validation
  • Auth is broken and you don't know why
  • Before deploying to production — pre-flight check
  • After upgrading auth packages or Next.js version
  • Periodic maintenance check

Step 1: Auto-Discover Project Stack

Run the same discovery logic as skills/auth-setup/SKILL.md → Step 0. This ensures setup and doctor use identical detection.

Scan for:

1a. Framework & Versions (same as setup Step 0a/0b):

  • next.config.* → Next.js (extract version from package.json)
  • App Router vs Pages Router
  • React version, Node.js version

1b. Auth Provider (same as setup Step 0d):

  • better-auth in deps → Better Auth
  • firebase in deps → Firebase
  • @clerk/nextjs, next-auth, @supabase/ssr → respective provider
  • If no auth detected → ❌ STOP: "No auth setup detected. Run /shipwithai-auth:setup first."

1c. ORM & Database (same as setup Step 0c):

  • drizzle.config.ts → Drizzle | prisma/schema.prisma → Prisma
  • Check database type from drizzle config or deps (SQLite, PostgreSQL, MySQL)

1d. Package Manager (same as setup Step 0f):

  • Lockfile detection

1e. UI Library (same as setup Step 0g):

  • components.json → shadcn/ui | Tailwind | MUI/Chakra/Mantine

1e. Existing Auth Pages & Routes (same as setup Step 0e):

  • Check for auth pages: src/app/(auth)/login/, src/app/(auth)/register/, etc.
  • Check for API routes: src/app/api/auth/
  • Check for middleware: src/middleware.ts, middleware.ts

1f. Auth-specific detection:

  • .env.local or .env → configured env vars
  • OAuth providers: check env vars for GOOGLE_CLIENT_ID, GITHUB_CLIENT_ID, APPLE_CLIENT_ID
  • Email: check for resend in deps or RESEND_API_KEY in env

Output the detection summary before proceeding:

🔍 Auth Doctor — Scanning project...

Framework:   Next.js 14.2.18 (App Router)
Provider:    Better Auth (better-auth@1.2.3)
ORM:         Drizzle (drizzle-orm@0.30.10)
Database:    SQLite (better-sqlite3)
Package mgr: npm
UI:          shadcn/ui (new-york)
OAuth:       Google ✓, GitHub ✗
Email:       Resend ✓

Step 2: Run Diagnostic Checks

Run each category. If $ARGUMENTS specifies a category, run ONLY that one. Otherwise run all 8.

Category 1: Environment Variables (env)

Check .env.local exists:

  • ❌ CRITICAL if missing entirely
  • Read .env.local (or .env as fallback)

Check provider-specific required vars:

ProviderRequired
Better AuthBETTER_AUTH_SECRET, BETTER_AUTH_URL
FirebaseNEXT_PUBLIC_FIREBASE_API_KEY, NEXT_PUBLIC_FIREBASE_PROJECT_ID, NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY

Check var quality (not just existence):

  • BETTER_AUTH_SECRET — must be ≥32 chars (recommend 64 hex chars from openssl rand -hex 32)
  • BETTER_AUTH_URL — must start with http:// or https://
  • NEXT_PUBLIC_FIREBASE_API_KEY — must start with AIza
  • FIREBASE_PRIVATE_KEY — must contain -----BEGIN

Check for test keys in production:

  • ⚠️ WARNING if BETTER_AUTH_URL=http://localhost in a project with NODE_ENV=production indicators
  • ⚠️ WARNING if RESEND_API_KEY=re_test_ (test key can't send to real emails)

Check OAuth var pairs:

  • If GOOGLE_CLIENT_ID exists → GOOGLE_CLIENT_SECRET must also exist (and vice versa)
  • If GITHUB_CLIENT_ID exists → GITHUB_CLIENT_SECRET must also exist
  • If APPLE_CLIENT_ID exists → APPLE_CLIENT_SECRET must also exist
  • ❌ CRITICAL if one exists without the other

Check email vars (if Resend detected):

  • RESEND_API_KEY — must start with re_
  • EMAIL_FROM — must be a valid email format
  • ⚠️ WARNING if EMAIL_FROM=onboarding@resend.dev — can only send to account owner email

Category 2: File Structure (files)

Check all required files per provider:

Better Auth required files:

src/db/schema.ts                              — Drizzle schema with auth tables
src/lib/db.ts                                 — Drizzle client
src/lib/auth.ts                               — Better Auth server config
src/lib/auth-client.ts                        — Better Auth client
src/app/api/auth/[...all]/route.ts            — API route handler
src/middleware.ts                              — Route protection middleware
src/app/(auth)/login/page.tsx                 — Login page
src/app/(auth)/register/page.tsx              — Register page
src/app/(auth)/forgot-password/page.tsx       — Forgot password page
src/app/(auth)/reset-password/page.tsx        — Reset password page
src/app/(protected)/layout.tsx                — Protected layout with session check
src/app/(protected)/dashboard/page.tsx        — Dashboard page
src/app/(protected)/dashboard/dashboard-client.tsx — Dashboard client component
src/components/icons.tsx                      — OAuth provider icons
.env.example                                  — Env var template
drizzle.config.ts                             — Drizzle Kit config

Firebase required files:

src/lib/firebase.ts                           — Client SDK init
src/lib/firebase-admin.ts                     — Admin SDK init
src/lib/firebase-session.ts                   — Session cookie helpers
src/lib/auth-server.ts                        — getServerUser() helper
src/app/api/auth/session/route.ts             — Session API with CSRF
src/middleware.ts                              — Route protection middleware
src/app/(auth)/login/page.tsx                 — Login page
src/app/(auth)/register/page.tsx              — Register page
src/app/(auth)/forgot-password/page.tsx       — Forgot password page
src/app/(auth)/reset-password/page.tsx        — Reset password page
src/app/(protected)/layout.tsx                — Protected layout with session verification
src/app/(protected)/dashboard/page.tsx        — Dashboard page
src/app/(protected)/dashboard/dashboard-client.tsx — Dashboard client component
src/components/icons.tsx                      — OAuth provider icons
.env.example                                  — Env var template

For each missing file: Report ❌ with the source asset path to copy from.

Cross-reference imports: For each existing file, check that its imports resolve:

  • Read the file, extract import ... from "..." statements
  • Check that aliased imports (@/lib/auth, @/components/icons, etc.) have corresponding files
  • ❌ CRITICAL if an import target doesn't exist (build will fail)

Category 3: Dependencies (deps)

Check provider packages installed:

  • Read package.json dependencies + devDependencies
  • Verify provider package exists and check version compatibility

Check for known breaking versions:

  • better-auth < 0.4.0 — major API changes
  • drizzle-kit with driver field instead of dialect — deprecated in 0.21+
  • shadcn > 2.1.0 with Tailwind v3 — incompatible (pitfall #44)
  • next >= 16 with middleware.ts — deprecated in favor of proxy.ts (pitfall #37)

Check peer dependency conflicts:

npm ls 2>&1 | grep "peer dep" | head -20

Check node_modules exists:

  • ❌ CRITICAL if missing

Category 4: Security (security)

Check .gitignore:

  • .env and .env.local must be listed
  • sqlite.db should be listed (if SQLite)
  • ❌ CRITICAL if .env not in .gitignore

Scan for hardcoded secrets in source files:

  • Scan src/ for patterns: sk_live_, sk_test_, re_, AIza, -----BEGIN, whsec_
  • Exclude .env* files and node_modules/
  • ❌ CRITICAL if found in .ts/.tsx source files

Check next.config for security headers:

  • ⚠️ WARNING if no security headers configured (X-Frame-Options, HSTS, CSP)
  • Reference: assets/config/next.config.ts

Check for better-sqlite3 in serverComponentsExternalPackages (Better Auth + SQLite):

  • Next.js 14: must be in experimental.serverComponentsExternalPackages
  • Next.js 15+: must be in serverExternalPackages
  • ❌ CRITICAL if missing — causes "Cannot find module" at runtime

Category 5: Dangerous Code Patterns (patterns)

These checks map directly to SKILL.md Critical Code Rules R1–R8.

R1 — Module-scope SDK instantiation:

  • Scan src/lib/email.ts for new Resend( at module scope (outside functions)
  • Scan src/lib/auth.ts for new Stripe( or new Resend( at module scope
  • ❌ CRITICAL — crashes during build/SSR because env vars unavailable at module evaluation

R4 — Better Auth middleware using auth() wrapper:

  • Scan src/middleware.ts for export { auth as middleware } or export default auth(
  • ❌ CRITICAL — auth() is Auth.js (NextAuth v5), not Better Auth

R5 — Firebase middleware decoding JWT:

  • Scan src/middleware.ts for atob(, Buffer.from(.*base64, firebase-admin, verifyIdToken, verifySessionCookie
  • ❌ CRITICAL — Edge Runtime cannot run Firebase Admin SDK

R2 — Redirect before session cookie (Firebase):

  • Scan login/register pages for router.push without preceding await createSessionCookie
  • ⚠️ WARNING — session may not persist

R3 — Sign-out order (Firebase):

  • Scan dashboard-client for sign-out logic
  • Server cookie delete should happen BEFORE client signOut()
  • ⚠️ WARNING if order is reversed

R7 — Missing Suspense wrapper:

  • Scan reset-password/page.tsx for useSearchParams() without <Suspense>
  • ❌ CRITICAL — next build fails in Next.js 14+

R8 — Missing files from checklist:

  • Already covered in Category 2, but double-check auth-client.ts specifically
  • ❌ CRITICAL — cascading import errors

Category 6: Middleware (middleware)

Check middleware exists:

  • Look for src/middleware.ts or middleware.ts
  • ⚠️ WARNING if missing

Check middleware pattern matches provider:

ProviderCorrect patternWrong pattern
Better Authrequest.cookies.get("better-auth.session_token")auth(), getSession(), headers()
Firebaserequest.cookies.get("__session")verifyIdToken, firebase-admin, atob

Check route matcher:

  • ⚠️ WARNING if no export const config = { matcher: [...] } — middleware runs on all routes including static assets
  • Verify matcher includes protected routes (/dashboard, /profile, etc.)
  • Verify matcher excludes auth routes (/login, /register, /api/auth)

Check for headers() import (Better Auth):

  • headers() from next/headers is NOT available in Edge Runtime middleware
  • ❌ CRITICAL if imported

Category 7: OAuth Configuration (oauth)

For each detected OAuth provider (Google, GitHub, Apple):

Check env vars complete:

  • Client ID + Client Secret must both be set
  • ❌ CRITICAL if one missing

Check auth config includes the provider:

  • Better Auth: socialProviders in src/lib/auth.ts should list the provider
  • Firebase: Provider must be enabled in Firebase Console (can't auto-check, but warn user)

Check callback URL format:

  • Better Auth: {BETTER_AUTH_URL}/api/auth/callback/{provider}
  • Firebase: https://{PROJECT}.firebaseapp.com/__/auth/handler
  • ⚠️ WARNING: remind user to verify callback URL is registered in provider console

Check for common Google OAuth mistakes (Firebase):

  • ⚠️ WARNING: remind about 5-step OAuth setup checklist in references/05-firebase-auth-guide.md
  • Testing mode: test user emails must be added in Google Cloud Console

Category 8: Database (database)

Better Auth + Drizzle:

Check drizzle.config.ts:

  • Must exist at project root
  • Must use dialect: "sqlite" (NOT driver: "better-sqlite")
  • ❌ CRITICAL if uses deprecated driver field

Check schema has auth tables:

  • Read src/db/schema.ts
  • Must contain: user, session, account, verification tables
  • ❌ CRITICAL if any missing

Check db.ts passes schema:

  • drizzle(client, { schema }) — schema must be imported and passed
  • ❌ CRITICAL if schema not passed — queries will fail

Check auth.ts passes schema to adapter:

  • drizzleAdapter(db, { provider: "sqlite", schema }) — schema must be passed
  • ❌ CRITICAL if schema missing in adapter config

Check database file exists (SQLite):

  • ⚠️ WARNING if sqlite.db doesn't exist — needs npx drizzle-kit push to create tables

Check migration status:

  • If drizzle/ directory has migration files, check they've been applied
  • ⚠️ WARNING if migrations exist but database doesn't have the tables

Step 3: Produce Health Report

After all checks complete, produce a scored report:

╔══════════════════════════════════════════════════╗
║          🔐 Auth Doctor — Health Report          ║
╠══════════════════════════════════════════════════╣
║ Provider:  Better Auth                           ║
║ Score:     18/22 checks passed                   ║
╚══════════════════════════════════════════════════╝

Category                 Status    Issues
─────────────────────────────────────────
1. Environment Variables   ✅       0
2. File Structure          ❌       2 missing files
3. Dependencies            ✅       0
4. Security                ⚠️       1 warning
5. Code Patterns           ✅       0
6. Middleware              ✅       0
7. OAuth Configuration     ❌       1 critical
8. Database                ⚠️       1 warning

──── CRITICAL (fix immediately) ─────────

❌ src/components/icons.tsx missing
   → Copy from plugin: assets/components/shared/icons.tsx

❌ GITHUB_CLIENT_ID set but GITHUB_CLIENT_SECRET missing
   → Add GITHUB_CLIENT_SECRET to .env.local

──── WARNINGS (review recommended) ──────

⚠️  No security headers in next.config
   → Merge from plugin: assets/config/next.config.ts

⚠️  sqlite.db not found — run: npx drizzle-kit push

Ordering rules:

  1. ❌ CRITICAL items first (will break at runtime)
  2. ⚠️ WARNING items second (works but risky)
  3. ✅ PASS items last (or omit for brevity)

Step 4: Offer to Fix

After presenting the report:

Found {N} issues ({X} critical, {Y} warnings).

Would you like me to fix them?
A) Fix all — apply all safe fixes automatically
B) Fix critical only — fix only ❌ items
C) Show me the fixes first — explain what I'd change, then confirm
D) Skip — I'll fix them manually

CRITICAL rules for fixing:

  • NEVER modify .env.local values without user confirmation (may contain real secrets)
  • NEVER delete files — only create missing ones or patch existing
  • For env var issues: show what needs to change, let user update
  • For missing files: copy from plugin assets (show source path)
  • For code pattern issues: show the diff before applying
  • For drizzle.config.ts driver → dialect: safe to auto-fix

Step 5: Post-Fix Verification

After fixes are applied, re-run ONLY the failed categories to confirm they now pass.

If all checks pass:

✅ All issues resolved! Auth setup is healthy.

Next steps:
- Run `npm run build` to verify the full build
- Test the auth flow: register → verify email → login → dashboard → sign out
- Review references/09-common-pitfalls.md for 60 production pitfalls

Auth Setup

Production-ready authentication for any web app in under 45 minutes. 2 auth providers (Better Auth & Firebase), Google OAuth, copy-paste UI components, and a verification script. GitHub & Apple OAuth coming soon.

When to Use

  • Starting a new project needing user authentication
  • Adding auth to an existing app (auto-detects and adapts to existing theme)
  • Migrating between auth providers
  • Setting up OAuth social login (Google, GitHub, Apple)
  • Need login/register page components

CRITICAL — New Project Scaffolding

If scaffolding a new Next.js project, never run create-next-app . in the current directory. Claude Code plugins (OMC, gstack) create dotfiles (.omc/, .claude/) that conflict with create-next-app, which requires a completely empty directory. The dotfiles are recreated by hooks between deletion and scaffolding, causing an infinite failure loop.

Correct pattern — scaffold in /tmp, pin to Next.js 14:

SCAFFOLD_DIR=/tmp/nextjs-scaffold-$RANDOM && \
npx create-next-app@14 "$SCAFFOLD_DIR" \
  --typescript --tailwind --eslint --app --src-dir \
  --import-alias "@/*" --use-npm --no-turbopack && \
cp -a "$SCAFFOLD_DIR"/. . && rm -rf "$SCAFFOLD_DIR"

Why @14 not @latest? Next.js 16 deprecated middleware.ts in favor of proxy.ts. All templates, guides, and middleware examples in this plugin use the middleware.ts convention (Next.js 14/15). Using @latest will install Next.js 16+ and the build will fail. See pitfall #37 for details.

Or scaffold into a named subdirectory, then move files up.

shadcn/ui: Use npx shadcn@2.1.0 init -d (NOT shadcn@2 or shadcn@latest). shadcn@2.5+ expects Tailwind v4's CSS-based config and fails with Next.js 14's tailwind.config.ts. After shadcn init, you MUST install tailwindcss-animate — shadcn adds it to tailwind.config.ts but does NOT auto-install it: {pm} install tailwindcss-animate (use package manager detected in Step 0). See pitfall #44.

Provider Decision Framework

Your situationBest choiceWhy
Full control, no vendor lock-inBetter AuthOpen-source, self-hosted, most flexible, zero cost
Google ecosystem or mobile + webFirebase AuthBest mobile/KMP support, free < 50K MAU

Note: Clerk, Auth.js, and Supabase Auth support is planned for a future release. Currently only Better Auth and Firebase Auth are fully supported.

Full comparison with cost analysis: references/01-choosing-provider.md

Quick Start

Step 0: Auto-Discover Project Stack (SILENT — no user interaction)

Before asking ANY questions, scan the project silently:

0a. Framework & Router:

  • Check next.config.* (.js, .mjs, .ts) → Next.js
  • Check astro.config.* → Astro
  • Check remix.config.* or @remix-run/* in deps → Remix
  • Check vite.config.* without framework deps → Vite
  • Check app/ directory → App Router | pages/ directory → Pages Router
  • If no framework detected → warn: "No supported framework detected. This plugin is designed for Next.js App Router."
  • If Pages Router only (no app/) → warn: "Pages Router detected. This plugin requires Next.js App Router (app/ directory)."

0b. Version Compatibility:

  • Read package.json and extract versions:
    • next — check major version (14, 15, 16+)
    • react — must be ≥18 for Server Components
    • node — check engines field or .nvmrc if exists
  • ❌ BLOCK if Next.js < 14: "This plugin requires Next.js 14+ with App Router."
  • ❌ BLOCK if React < 18: "React 18+ required for Server Components."
  • ⚠️ WARNING if Next.js ≥ 16: "Next.js 16 detected. middleware.ts is deprecated — plugin will use proxy.ts pattern instead."
  • Store version for later decisions:
    • Next.js 14 → experimental: { serverComponentsExternalPackages: [...] }
    • Next.js 15+ → serverExternalPackages: [...]

0c. Database ORM:

  • Check drizzle.config.ts or drizzle.config.js → Drizzle
  • Check prisma/schema.prisma → Prisma
  • Fallback: check package.json for drizzle-orm or @prisma/client
  • If both detected → prefer the one with config file
  • If none detected → will ask user in Q3 (don't block)

0d. Existing Auth:

  • Check src/lib/auth.ts + better-auth in deps → Better Auth already installed
  • Check src/lib/firebase.ts + firebase in deps → Firebase already installed
  • Check @clerk/nextjs in deps → Clerk detected
  • Check next-auth in deps → Auth.js/NextAuth detected
  • Check @supabase/ssr in deps → Supabase Auth detected
  • If auth detected → ⚠️ WARNING: "Existing auth setup detected ({provider}). Running setup may conflict. Run /shipwithai-auth:doctor first to check health, or confirm you want to replace it."

0e. Existing Auth Pages & Routes:

  • Check for existing pages: src/app/(auth)/login/, src/app/login/, app/login/
  • Check for existing API routes: src/app/api/auth/, app/api/auth/
  • Check for existing middleware: src/middleware.ts, middleware.ts
  • If found → store list, will warn before overwriting in Step 2

0f. Package Manager:

  • pnpm-lock.yaml → pnpm
  • yarn.lock → yarn
  • bun.lockb → bun
  • package-lock.json → npm
  • Default to npm if no lockfile found

0g. UI Library:

  • Check components.json → shadcn/ui (read style and baseColor fields)
  • Check @mui/material in deps → MUI
  • Check @chakra-ui/react in deps → Chakra UI
  • Check @mantine/core in deps → Mantine
  • Check for Tailwind: tailwind.config.* or tailwindcss in deps
  • If shadcn/ui detected → skip shadcn init in setup, only add missing components
  • If non-shadcn UI library detected → ⚠️ WARNING: "Detected {library}. Auth components use shadcn/ui — you may need to adapt styling."

0h. Existing Design System (Context Project):

  • This is detected via Question 5 (cannot auto-detect parent project path)
  • But if globals.css already has shadcn CSS variables → Scenario A (skip theme generation)

Show discovery summary to user:

🔍 Project scan complete

Framework:     Next.js 14.2.18 (App Router)
Package mgr:   npm
ORM:           Drizzle (drizzle-orm@0.30.10)
UI:            shadcn/ui (new-york style)
Existing auth: None detected
Existing pages: /dashboard (protected)
Node.js:       v20.11.0
React:         18.3.1

Ready to set up authentication.

If critical issues found, STOP and report:

⛔ Cannot proceed:
- Next.js 13 detected — requires Next.js 14+ with App Router
- No `app/` directory found — Pages Router not supported

Fix these issues first, then re-run /shipwithai-auth:setup

Step 1: Choose provider

Ask user which provider using AskUserQuestion. Present options:

  1. Better Auth (Recommended) — Free, self-hosted, full control. Open-source, no vendor lock-in. Best for most projects.
  2. Firebase Auth — Google ecosystem, best for mobile/KMP apps. Free < 50K MAU.
  3. Clerk — ⚠️ Coming Soon
  4. Supabase Auth — ⚠️ Coming Soon
  5. Auth.js — ⚠️ Coming Soon

If user selects a "Coming Soon" provider: Do NOT proceed. Warn and re-ask with only supported options.

If unsure, ask:

  • "Need mobile support (KMP/React Native)?" → Firebase Auth
  • "Want self-hosted, full control, zero cost?" → Better Auth
  • "Using Google ecosystem (Firebase, GCP)?" → Firebase Auth
  • "Building a SaaS with custom auth logic?" → Better Auth

Step 1a: Choose OAuth

Ask user which social login using AskUserQuestion. Present options:

  1. Google only (Recommended) — Most common, covers 90%+ of users
  2. Google + GitHub — ⚠️ GitHub Coming Soon
  3. Google + GitHub + Apple — ⚠️ GitHub & Apple Coming Soon
  4. None — Email/password only, add social login later

If user selects an option with "Coming Soon" providers: Warn, then proceed with Google only. Mention /shipwithai-auth:add-oauth for future providers.

Step 1b: Detect theme context

ALWAYS run this step — even for new projects. Use Step 0 discovery results to auto-classify where possible.

There are 4 scenarios:

ScenarioConditionglobals.css Action
AExisting project with shadcn/ui (detected in 0g)SKIP — use existing CSS variables
BExisting project with Tailwind but no shadcn/ui (detected in 0g)MERGE — add shadcn/ui vars to existing globals.css
CStandalone new project (no parent design system)AUTO-SELECT — AI picks Ocean or Sunrise preset
DNew project inside/alongside existing projectINHERIT — map parent's design tokens to shadcn/ui vars

Auto-classification from Step 0:

  • If Step 0 detected shadcn/ui (components.json exists) → Scenario A — skip to Step 2, no question needed
  • If Step 0 detected Tailwind but no shadcn/ui → Scenario B — confirm with user, then merge
  • If Step 0 detected existing auth pages → likely Scenario A or B, confirm with user

Only ask Question 5 if scenario is ambiguous:

  • If this is a new project being scaffolded (no existing globals.css) → ask: "Is this new app part of an existing project with its own design system?"
  • If YES → get the parent project path and run: npx ts-node scripts/detect-theme.ts /path/to/new-app --context /path/to/parent-project
  • If NO → Scenario C, proceed with AI theme auto-selection (see below)

Scenario C (NEW PROJECT) — AI auto-selects theme:

Two curated theme presets are available in assets/themes/. Do NOT ask the user to choose — pick automatically based on project signals:

ThemeFileFontBest for
Oceanassets/themes/ocean.cssDM SansSaaS, dashboard, dev tools, API, analytics, admin, B2B
Sunriseassets/themes/sunrise.cssOutfitConsumer, blog, shop, community, education, portfolio, e-commerce

Auto-selection logic (SILENT — no user interaction):

  1. Read package.json → name and description fields
  2. Read README.md first paragraph (if exists)
  3. Match keywords against domain signals:
    • SaaS / dashboard / admin / api / analytics / dev / tool / platform / monitor / deploy → Ocean
    • blog / shop / store / community / social / education / learn / portfolio / landing / market → Sunrise
  4. If ambiguous or no signals → Ocean (default)

After selecting theme:

  1. Run npx shadcn@2.1.0 init -d first (creates default globals.css)
  2. Overwrite globals.css with the selected theme preset file
  3. Add the theme's Google Font import at the top of globals.css:
    • Ocean: @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap');
    • Sunrise: @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&display=swap');
  4. Update layout.tsx to use the theme's font instead of default Geist:
    • Ocean: import { DM_Sans } from "next/font/google" → const font = DM_Sans({ subsets: ["latin"] })
    • Sunrise: import { Outfit } from "next/font/google" → const font = Outfit({ subsets: ["latin"] })
  5. Ocean is dark-first → set <html className="dark"> in layout.tsx
  6. Show the selected theme in the Step 0 summary:
    Theme:         Ocean (dark, DM Sans) — auto-selected for SaaS project
    

Scenario D (INHERIT) — what to do:

  • CRITICAL ordering: Run npx shadcn@2.1.0 init -d FIRST, then apply the inherited theme. shadcn init overwrites globals.css with default variables — if you apply the inherited theme first, shadcn will destroy it.
  • The script scans the parent's CSS files and extracts design tokens (backgrounds, text colors, accents, borders, fonts, border-radius)
  • It maps them to shadcn/ui CSS variables and outputs a shadcnMapping with dark and light mode values
  • After shadcn init completes, overwrite globals.css with the inherited theme mapping
  • Add the parent's Google Fonts @import to globals.css
  • Set className="dark" on <html> if the parent is dark-first
  • Update layout.tsx to use the parent's font-family instead of default Geist

Key rule: Auth components use shadcn/ui CSS variables (--primary, --background, etc.). The theme detection ensures these variables match the surrounding project's design — whether it's the same project (A/B), a parent/sibling project (D), or an auto-selected preset (C).

See references/10-existing-project-integration.md for detailed adaptation steps.

Step 2: Follow provider guide

ProviderGuide
Better Authreferences/02-better-auth-guide.md
Firebase Authreferences/05-firebase-auth-guide.md

Step 3: Email provider (Better Auth only)

Skip this step for Firebase — Firebase handles email delivery automatically.

For Better Auth — you MUST ask the user before proceeding. Do NOT skip this question. Do NOT assume console-only. STOP and ASK:

"How should auth emails be sent? (verification emails, password reset links)

A) Resend (Recommended) — free tier: 100 emails/day, simple API, works in 2 minutes B) Console only (Development) — emails log to terminal, no real delivery C) Other provider — you'll configure SendGrid/Nodemailer/etc. yourself"

WAIT for the user's answer before writing any auth config files.

If A (Resend):

  1. Install: {pm} install resend (use package manager detected in Step 0)
  2. Add to .env.local: RESEND_API_KEY=re_xxxxx and EMAIL_FROM=onboarding@resend.dev
  3. Create src/lib/email.ts with the sendAuthEmail helper from the Better Auth guide → "Email Provider — Resend" section
  4. Update sendVerificationEmail and sendResetPassword callbacks in src/lib/auth.ts to use sendAuthEmail
  5. IMPORTANT — Tell the user after setup: "With Resend's free tier and onboarding@resend.dev as sender, emails can ONLY be delivered to the email address that owns your Resend account. To send to any email, verify your own domain at resend.com/domains and change EMAIL_FROM to auth@yourdomain.com."

If B (Console):

  1. Keep the console.log stubs in auth config (already the default)
  2. Tell user: "Check your terminal for verification/reset links during development"

If C (Other):

  1. Keep the console.log stubs as placeholder
  2. Tell user to replace the callbacks with their email service

Step 4: Add social login

Currently supported: Google OAuth only. GitHub and Apple are coming soon.

See references/07-oauth-social-login.md for Google setup across all providers.

Step 5: Database schema

See references/08-database-auth-schema.md for Drizzle/Prisma/Supabase schemas.

Step 6: Add UI components

Use Step 0 discovery results:

  • If shadcn/ui already detected (0g) → skip shadcn init, only run npx shadcn@2.1.0 add button input label card separator for missing components
  • If shadcn/ui NOT detected → run npx shadcn@2.1.0 init -d first, then add components. Remember: for Scenario D, apply inherited theme AFTER shadcn init.
  • If existing auth pages detected (0e) → ⚠️ WARN user before overwriting: "Found existing {page}. Overwrite with plugin component?"
  • Use detected package manager (0f) for all install commands

Components are organized by provider. Copy from the correct folder:

  • Better Auth: assets/components/better-auth/
  • Firebase Auth: assets/components/firebase/
  • Shared (provider-agnostic): assets/components/shared/

REQUIRED — Core auth pages (MUST copy all of these):

FileSource folderPlace atPurpose
login-page.tsx{provider}/app/(auth)/login/page.tsxLogin with email + social buttons
register-page.tsx{provider}/app/(auth)/register/page.tsxRegistration form
forgot-password.tsx{provider}/app/(auth)/forgot-password/page.tsxPassword reset request (sends email)
reset-password.tsx{provider}/app/(auth)/reset-password/page.tsxComplete password reset (token from email → new password)
protected-layout.tsx{provider}/app/(protected)/layout.tsxServer-side session verification
dashboard-client.tsx{provider}/app/(protected)/dashboard/dashboard-client.tsxSign-out button (client component)
dashboard-page.tsxshared/app/(protected)/dashboard/page.tsxProtected dashboard page
icons.tsxshared/src/components/icons.tsxOAuth provider SVG icons (Google, GitHub) — required by login/register pages
globals.cssshared/app/globals.cssTailwind CSS directives + shadcn/ui variables

RECOMMENDED — User management (copy unless user explicitly declines):

FileSource folderPlace atPurpose
user-profile.tsx{provider}/app/(protected)/profile/page.tsxProfile view + update name + sign out + delete account

OPTIONAL:

  • auth-provider-buttons.tsx — Standalone OAuth buttons (already included in login/register pages)

Copy from assets/config/:

  • next.config.ts — Security headers (X-Frame-Options, HSTS, etc.) — merge into existing config
  • drizzle.config.ts — Drizzle Kit config with dialect: "sqlite" (Better Auth only) — copy to project root

Where {provider} = better-auth or firebase depending on the chosen provider.

CRITICAL for Firebase Auth — File creation checklist: You MUST create ALL of these files for Firebase to work. Do NOT skip any:

  1. src/lib/firebase.ts — Client SDK init (from firebase.config.ts → "Client SDK Setup")
  2. src/lib/firebase-admin.ts — Admin SDK init (from firebase.config.ts → "Admin SDK Setup")
  3. src/lib/firebase-session.ts — createSessionCookie() + clearSessionAndSignOut() helpers (from firebase.config.ts → "Session Cookie Helper" + "Sign-Out Helper")
  4. src/lib/auth-server.ts — getServerUser() helper (from firebase.config.ts → "Server Component Auth Check"). Import this in BOTH (protected)/layout.tsx AND (protected)/dashboard/page.tsx — do NOT duplicate the function inline
  5. src/app/api/auth/session/route.ts — Session API with rate limiting + CSRF (from firebase.config.ts → "Session Cookie API Route"). The POST handler MUST be wrapped in try/catch — return 401 on invalid token, never 500
  6. src/middleware.ts — Route protection (from assets/middleware/firebase/nextjs-middleware.ts)
  7. app/globals.css — Tailwind v3 directives (@tailwind base; @tailwind components; @tailwind utilities;) + shadcn/ui hsl CSS variables — layout.tsx imports this file. Copy from assets/components/shared/globals.css

CRITICAL for Firebase Auth — Google OAuth Setup: If using Google sign-in with signInWithPopup, you MUST complete the 5-step OAuth setup checklist in references/05-firebase-auth-guide.md → "Google OAuth Setup Checklist". Without it, sign-in will fail with 400 Bad Request. Key points:

  1. Enable Google provider in Firebase Console (not just Google Cloud Console)
  2. Configure the correct OAuth client ID in Google Cloud Console (must match Firebase's Web client ID)
  3. Add https://<PROJECT>.firebaseapp.com/__/auth/handler to Authorized redirect URIs (NOT /api/auth/callback/google — that's Auth.js)
  4. If OAuth consent screen is in Testing mode, add test user emails → Read references/05-firebase-auth-guide.md → "Google OAuth Setup Checklist" for full steps

CRITICAL for Firebase Auth — Session flow:

  1. After sign-in/register, call createSessionCookie(result.user) and await it
  2. Only THEN redirect to /dashboard
  3. On sign-out, call clearSessionAndSignOut() FIRST (clears server cookie + Firebase), then redirect
  4. Never rely on onAuthStateChanged for the initial login redirect

CRITICAL for Firebase Auth Security:

  1. Set NEXT_PUBLIC_APP_URL env var — required for CSRF protection on session endpoint
  2. Place protected pages under app/(protected)/ and use protected-layout.tsx to verify sessions server-side (middleware only checks cookie existence, NOT validity)
  3. The session DELETE handler revokes Firebase refresh tokens — stolen sessions are invalidated immediately
  4. Error messages use generic text — never expose Firebase error codes to users

CRITICAL for Firebase Auth — Middleware routes: Only include routes in protectedRoutes that have actual pages. Default: ["/dashboard"]. Add /profile only if user-profile.tsx was copied. Do NOT add /settings or /profile unless those pages exist.

CRITICAL for Firebase Auth — Middleware security: The middleware runs on Edge Runtime and CANNOT use Firebase Admin SDK. It MUST only check cookie existence (request.cookies.get("__session")?.value). Do NOT attempt to decode, parse, or validate the JWT in middleware — Base64-decoding the payload without verifying the cryptographic signature gives a false sense of security. An attacker can craft a fake JWT that passes the decode check. Real verification happens in (protected)/layout.tsx via adminAuth.verifySessionCookie().

CRITICAL for Better Auth — File creation checklist: You MUST create ALL of these files for Better Auth to work. Do NOT skip any:

  1. src/db/schema.ts — Drizzle schema with Better Auth tables (from assets/db/better-auth-schema.ts)
  2. src/lib/db.ts — Drizzle client (from assets/db/better-auth-db.ts). MUST import and pass schema to drizzle(client, { schema })
  3. src/lib/auth.ts — Server config (from assets/config/better-auth.config.ts). MUST pass schema to drizzleAdapter: drizzleAdapter(db, { provider: "sqlite", schema })
  4. src/lib/auth-client.ts — Client setup (from better-auth.config.ts → "Client Setup" section)
  5. src/app/api/auth/[...all]/route.ts — API route handler
  6. src/middleware.ts — Route protection using cookie-based pattern (from assets/middleware/better-auth/nextjs-middleware.ts). Do NOT use auth() wrapper — that's Auth.js, not Better Auth (see pitfall #43)
  7. src/app/(protected)/layout.tsx — Server-side session verification
  8. .env.local — Copy from assets/config/better-auth.env.example and fill in values
  9. drizzle.config.ts — Copy from assets/config/drizzle.config.ts. MUST use dialect: "sqlite" (NOT driver: "better-sqlite" — removed in drizzle-kit 0.21+). See pitfall #48.
  10. Database migration — Create tables with npx drizzle-kit push (or npx @better-auth/cli generate && npx @better-auth/cli migrate)
  11. UI components — Copy login, register, forgot-password, reset-password, dashboard from assets/components/better-auth/ (shared components from assets/components/shared/)
  12. reset-password.tsx already includes a <Suspense> wrapper — useSearchParams() requires this in Next.js 14+ App Router or the build fails. Do NOT remove the Suspense wrapper.
  13. shadcn/ui: Use npx shadcn@2.1.0 (NOT @latest or @2) to avoid Tailwind v4 conflicts with Next.js 14. See pitfall #44.

CRITICAL for Better Auth — next.config.ts compatibility: When adding better-sqlite3 or other native packages to next.config.ts:

  • Next.js 14: Use experimental: { serverComponentsExternalPackages: ["better-sqlite3"] }
  • Next.js 15+: Use serverExternalPackages: ["better-sqlite3"] Check the project's Next.js version in package.json BEFORE writing the config. Using the wrong syntax causes: Unrecognized key(s) in object: 'serverExternalPackages'.

CRITICAL for Better Auth — Session flow:

  1. Better Auth manages sessions via cookies (better-auth.session_token) — no manual cookie creation needed (unlike Firebase)
  2. cookieCache is enabled by default (5 min) — session changes (role updates, email verification) take up to 5 minutes to propagate
  3. In Server Components, use auth.api.getSession({ headers: await headers() }) — this verifies the session cryptographically
  4. In middleware, check the better-auth.session_token cookie directly — do NOT use auth() wrapper (that's Auth.js, see pitfall #43). Do NOT use headers() from next/headers in middleware (Edge Runtime incompatible)

NOTE for Better Auth: The forgot-password page sends a reset link via email. You MUST also copy reset-password.tsx to app/(auth)/reset-password/page.tsx to handle the link destination. Without it, users get a 404.

CRITICAL for shadcn/ui Button: If using buttonVariants in a Server Component (e.g., home page), extract buttonVariants into a separate file WITHOUT "use client" directive. The Button component needs "use client" but buttonVariants is a pure function that can run on the server.

Step 7: Verify

Run scripts/verify-auth-setup.ts to confirm auth works end-to-end. The script now includes dangerous code pattern detection — it catches module-scope SDK instantiation, wrong middleware patterns, missing Suspense wrappers, and other pitfalls automatically.

Step 8: Generate README (CRITICAL — must run, even after compaction)

Copy the provider's assets/templates/providers/{better-auth|firebase}/README.md.tmpl, substitute placeholders, write to end-user project root as README.md. Do NOT improvise — template is source of truth.

MANDATORY FLOW: Read → Ask → Write. Never call Write on README.md without first checking existence and asking the user. The Write tool fails with Error writing file when the target exists and has not been Read in this session — this is a guard against silent overwrites.

Step 8a — Existing README guard (MUST run before any Write):

  1. Check existence FIRST. Use Glob with pattern README.md (or Bash: ls README.md 2>/dev/null) to detect.
  2. If README.md does NOT exist → skip to Step 8b, proceed with Write directly.
  3. If README.md EXISTS: a. Read it first (Read README.md) — required before any later Write to that path AND so you can summarize current content to the user. b. Call AskUserQuestion with these 3 options (do NOT silently pick one):
    • A) Append AUTH section (default — preserves existing content, adds auth docs at the end via Edit)
    • B) Overwrite (backup current → README.md.bak via Bash: cp README.md README.md.bak, then Write new README)
    • C) Save separately as README.AUTH.md (Write to a new path; existing README untouched) c. Wait for the user's answer. Do NOT proceed on assumption. d. Execute the chosen branch:
    • A (Append): Use Edit to append the rendered template under a new ## Authentication section. Do NOT use Write (it would overwrite).
    • B (Overwrite): Run backup Bash command first → verify .bak exists → then Write README.md with new content.
    • C (Separate): Write to README.AUTH.md instead of README.md. Mention the new file in the final summary.

Recovery — if Write README.md already failed with Error writing file: The file exists and was not Read. Do NOT retry the same Write. Instead: Read README.md → run Step 8a's AskUserQuestion → execute the chosen branch.

Step 8b — Substitute placeholders (double-brace {{NAME}}):

PlaceholderSourceFallback chain
{{PROJECT_NAME}}package.json name1) strip @scope/ → 2) basename(cwd) → 3) My App
{{NEXT_VERSION}}Step 0b14+ if unknown
{{ORM}}Step 0cDrizzle (Better Auth default)

Provider name is pre-resolved by selecting the correct template file (firebase/ vs better-auth/), not via placeholder.

Step 8c — Process conditional blocks <!-- IF key=value -->...<!-- /IF -->:

  • oauth=google → keep if Step 1a included Google, else delete (and remove markers).
  • email=resend|console|other → keep matching Step 3 choice, delete the rest.

Step 8d — Verify (mandatory): No raw {{ remains. No raw <!-- IF remains. Every env var in .env.example appears in the README env table. At least one link to provider's console (Firebase / Google Cloud / Resend). No orphan intra-doc anchor links. If any check fails → re-run substitution.

CRITICAL CODE RULES — Violating any of these causes runtime crashes

These rules are mandatory. They are extracted from 60 production pitfalls (references/09-common-pitfalls.md) and represent the most common causes of auth failures. Claude MUST follow these rules when generating ANY auth code:

R1 — NEVER instantiate SDK clients at module scope. new Resend(process.env.X) or new Stripe(process.env.X) at the top of a file crashes during build/SSR because env vars aren't available at module evaluation time. Use lazy initialization (singleton getter function) or create instances inside handler functions. Copy assets/config/email.ts for the correct Resend pattern. (#50)

R2 — ALWAYS await session cookie BEFORE redirect. router.push("/dashboard") without await createSessionCookie() first → middleware bounces user back to /login because cookie doesn't exist yet. Firebase: await createSessionCookie(user) then redirect. Better Auth: handled automatically via cookie. (#22)

R3 — Sign-out: clear server cookie FIRST, then client, then redirect. Calling signOut() (client) before DELETE /api/auth/session (server) leaves an orphan server cookie. Order: server delete → client signOut → window.location.href = "/login". (#23)

R4 — NEVER use auth() wrapper in middleware for Better Auth. auth() is Auth.js (NextAuth v5), NOT Better Auth. Better Auth middleware checks request.cookies.get("better-auth.session_token") directly. Using auth() gives "auth is not a function". (#43)

R5 — NEVER decode JWT in middleware for Firebase. Middleware runs on Edge Runtime — no Firebase Admin SDK. Only check cookies.get("__session")?.value existence. Real verification happens in (protected)/layout.tsx via adminAuth.verifySessionCookie(). Base64-decoding without crypto verification gives false security. (#28)

R6 — ALWAYS copy email.ts from assets/config/email.ts template. Do NOT write email helper code from scratch. The template has correct lazy-init, dev fallback (console.log), and production guard. Inline code examples in guides may be simplified — the template is the source of truth.

R7 — useSearchParams() requires <Suspense> wrapper in Next.js 14+ App Router. reset-password.tsx uses useSearchParams() — without Suspense, next build fails. The template already includes it. Do NOT remove the Suspense wrapper. (#47)

R8 — Copy ALL files in the provider checklist. Skipping any file (e.g., auth-server.ts for Firebase, auth-client.ts for Better Auth) causes cascading import errors. Use the numbered checklist in the CRITICAL section above — every item is required.

Full 60 pitfalls: references/09-common-pitfalls.md

Implementation Checklist

  • Choose auth provider (use decision framework above)
  • Install packages + set environment variables
  • Configure auth server/client
  • Set up database schema + run migrations
  • Mount API routes/handlers
  • Add OAuth providers (Google only — GitHub & Apple coming soon)
  • Create login/register UI pages
  • Add middleware for protected routes
  • Test: sign up → verify email → sign in → sign out → reset password
  • Test: OAuth sign in → account linking
  • Add security headers to next.config.ts (use assets/config/next.config.ts template)
  • Add protected layout for server-side session verification (Firebase)
  • Set NEXT_PUBLIC_APP_URL for CSRF protection (Firebase)
  • Enable rate limiting for production (see 05-firebase-auth-guide.md Security Hardening section)
  • Run verify-auth-setup script

Commands 2

Auth Doctor

You are an expert authentication engineer performing a health check on an existing auth setup.

BEFORE ANYTHING ELSE: Read skills/auth-doctor/SKILL.md for the complete diagnostic guide, check categories, and fix procedures.

What This Command Does

Scans the project for auth-related issues across 8 categories:

  1. Environment Variables — missing/empty keys, test keys in production, unpaired OAuth secrets
  2. File Structure — missing required files per provider checklist
  3. Dependencies — wrong versions, missing packages, peer dep conflicts
  4. Security — hardcoded secrets, .gitignore gaps, exposed API keys
  5. Dangerous Code Patterns — module-scope SDK init (R1), wrong middleware (R4/R5), missing Suspense (R7)
  6. Middleware — wrong pattern for provider, Edge Runtime violations, missing route matcher
  7. OAuth Configuration — incomplete provider setup, wrong callback URLs, missing redirect URIs
  8. Database — schema tables missing, migration pending, connection errors

Execution

If $ARGUMENTS specifies an area (e.g., env, middleware, patterns), run ONLY that category. If $ARGUMENTS is empty or all, run ALL 8 categories.

Follow skills/auth-doctor/SKILL.md exactly — it contains the diagnostic steps, pass/fail criteria, and fix procedures.

CRITICAL: Do NOT auto-fix anything without asking the user first. Present the health report, then offer to fix.

Auth Setup Wizard

You are an expert authentication engineer. Guide the user through setting up production-ready auth for their project.

BEFORE ANYTHING ELSE: Read the skill at skills/auth-setup/SKILL.md for the full decision framework, file creation checklists, and critical warnings. Also read skills/auth-setup/references/09-common-pitfalls.md to avoid known issues.

Step 0: Auto-Discover Project Stack (SILENT)

Before asking ANY questions, silently scan the project. Follow skills/auth-setup/SKILL.md → Step 0 exactly.

Scan for:

  1. Framework — next.config.* → Next.js (check version: 14/15/16+)
  2. Router — app/ → App Router | pages/ → Pages Router (❌ block if no App Router)
  3. Version compat — React ≥18, Node ≥18. Block if incompatible.
  4. ORM — drizzle.config.ts → Drizzle | prisma/schema.prisma → Prisma | deps fallback
  5. Existing auth — better-auth, firebase, @clerk/nextjs, next-auth, @supabase/ssr in deps
  6. Existing pages — (auth)/login/, api/auth/, middleware.ts, README.md at project root (used by Step 2m)
  7. Package manager — lockfile detection (pnpm/yarn/bun/npm)
  8. UI library — components.json → shadcn/ui | Tailwind | MUI/Chakra/Mantine
  9. Design system — existing globals.css with shadcn CSS vars → Scenario A

Show summary to user (see SKILL.md for format). If critical issues found → STOP.

If existing auth detected → warn and suggest /shipwithai-auth:doctor first. Only proceed if user confirms.

Store all results — use them to skip questions and adapt code generation below.

Step 1: Gather Requirements

If $ARGUMENTS specifies a provider, skip Question 1.

Smart skipping based on Step 0:

  • If ORM detected → pre-fill Question 3, ask user to confirm instead of choosing
  • If existing auth detected → warn about conflict before Question 1
  • If shadcn/ui detected → Scenario A confirmed, skip Question 5

Ask questions ONE AT A TIME using AskUserQuestion:

Question 1: "Which auth provider do you want to use?" Options:

  • Better Auth (Recommended) — Free, self-hosted, full control. Open-source, no vendor lock-in. Best for most projects.
  • Firebase Auth — Google ecosystem, best for mobile/KMP apps. Free < 50K MAU.
  • Clerk — ⚠️ Coming Soon. Fastest setup, pre-built UI, managed service.
  • Supabase Auth — ⚠️ Coming Soon. Postgres-native with Row Level Security. Best if already using Supabase.
  • Auth.js — ⚠️ Coming Soon. Lightweight, zero cost.
  • Not sure — help me choose

If user selects a "Coming Soon" provider: Do NOT proceed. Show:

⚠️ {provider} support is coming soon! Currently supported providers:
  1. Better Auth — self-hosted, full control, zero cost
  2. Firebase Auth — Google ecosystem, mobile/KMP ready

Would you like to choose one of these instead?

Then re-ask Question 1 with only the 2 supported options.

If "Not sure", ask follow-up:

  • "Do you need mobile app support (KMP/React Native)?" → Firebase Auth
  • "Do you want full control, self-hosting, zero cost?" → Better Auth
  • "Using Google ecosystem (Firebase, GCP)?" → Firebase Auth
  • "Building a SaaS with custom auth logic?" → Better Auth

Question 2: "Which social login providers do you need?" Options:

  • Google only — Most common, covers 90%+ of users (Recommended)
  • Google + GitHub — ⚠️ GitHub Coming Soon
  • Google + GitHub + Apple — ⚠️ GitHub & Apple Coming Soon
  • None — Email/password only, add social login later

If user selects an option with "Coming Soon" providers: Show:

⚠️ {providers} support is coming soon! Currently only Google OAuth is supported.

I'll set up Google login now. The other providers can be added later via /shipwithai-auth:add-oauth when available.

Then proceed with Google only.

Question 3: "Which database ORM are you using?" (Better Auth, Auth.js, Supabase only)

Skip for Clerk and Firebase — they manage their own database.

If Step 0 detected an ORM: Pre-fill and confirm instead of asking:

  • "I detected Drizzle ORM in your project (drizzle.config.ts found). I'll use that — OK?"
  • Only ask the full question if no ORM was detected:

Options:

  • Drizzle ORM (Recommended)
  • Prisma
  • None / Not sure (I'll help you choose)

Question 4: Email provider (Better Auth, Auth.js, Supabase only)

Skip for Clerk and Firebase — they handle email delivery automatically.

For Better Auth, Auth.js, and Supabase — you MUST ask this. Do NOT skip. Do NOT assume console-only. STOP and ASK:

"How should auth emails be sent? (verification emails, password reset links)

A) Resend (Recommended) — free tier: 100 emails/day, simple API, works in 2 minutes B) Console only (Development) — emails log to terminal, no real delivery C) Other provider — you'll configure SendGrid/Nodemailer/etc. yourself"

WAIT for the user's answer before writing any auth config files.

Question 5: Project context (skip if Step 0 already resolved the scenario)

Auto-skip rules from Step 0:

  • If shadcn/ui detected (components.json exists) → Scenario A — skip this question entirely
  • If existing globals.css has shadcn CSS vars (:root with --background, --foreground, etc.) → Scenario A — skip
  • If Tailwind detected but no shadcn/ui → Scenario B — skip question, proceed with merge

Only ask if the project is new (being scaffolded) or scenario is ambiguous:

"Where will this auth app live?

A) Standalone project — new project with no existing design system B) Inside/alongside an existing project — there's a parent or sibling project with its own design system (e.g., Astro, Next.js, Remix site with custom theme) C) Not sure"

Theme scenarios (4 total):

ScenarioConditionglobals.css Action
AExisting project with shadcn/ui (detected in Step 0)SKIP — use existing CSS variables
BExisting project with Tailwind but no shadcn/uiMERGE — add shadcn/ui vars to existing globals.css
CStandalone new project (no parent design system)AUTO-SELECT — AI picks Ocean or Sunrise preset
DNew project inside/alongside existing projectINHERIT — map parent's design tokens to shadcn/ui vars

If answer is A: Skip — use existing theme.

If answer is C (→ Scenario C): AI auto-selects a theme preset. Do NOT ask the user. Read package.json name/description + README to infer project domain:

  • SaaS / dashboard / admin / api / analytics / dev / tool → Ocean (assets/themes/ocean.css, DM Sans, dark-first)
  • Blog / shop / community / education / portfolio / landing → Sunrise (assets/themes/sunrise.css, Outfit, light-first)
  • Ambiguous → Ocean (default)

If answer is B (→ Scenario D): Ask for the parent/sibling project path. Then run theme detection with context: npx ts-node scripts/detect-theme.ts /path/to/new-app --context /path/to/parent-project

CRITICAL for Scenario D: Run npx shadcn@2.1.0 init -d FIRST, then apply the inherited theme. If you apply the inherited theme first, shadcn init will overwrite globals.css with defaults and destroy the inherited design tokens.

This question exists because: When creating a new app inside an existing project, the new app should inherit the parent's design tokens (fonts, colors, border-radius). Without this, the new app gets a generic default theme that looks disconnected from the parent project.

Step 2: Execute Setup

Based on the answers, follow this exact sequence:

2a. Read the Provider Guide

Read the appropriate reference file:

  • Better Auth → skills/auth-setup/references/02-better-auth-guide.md
  • Firebase → skills/auth-setup/references/05-firebase-auth-guide.md
  • Clerk → references/03-clerk-guide.md (Coming Soon)
  • Auth.js → references/04-authjs-guide.md (Coming Soon)
  • Supabase → references/06-supabase-auth-guide.md (Coming Soon)

CRITICAL: Follow the guide EXACTLY. Do NOT generate code from memory — copy patterns from the guide and asset files.

2b. Apply Version-Specific Config

Use the Next.js version detected in Step 0 (do NOT re-read package.json):

  • Next.js 14: experimental: { serverComponentsExternalPackages: ["better-sqlite3"] }
  • Next.js 15: serverExternalPackages: ["better-sqlite3"]
  • Next.js 16+: Use proxy.ts instead of middleware.ts
  • If scaffolding a new project: pin to npx create-next-app@14

2c. Install Dependencies

Use the package manager detected in Step 0 (default: npm). Replace {pm} below:

  • npm → npm install
  • pnpm → pnpm add
  • yarn → yarn add
  • bun → bun add

Run the appropriate {pm} install command for the chosen provider.

  • If email = Resend, also run: {pm} install resend
  • For UI components:
    • If shadcn/ui already detected in Step 0 → skip init, only add missing components: npx shadcn@2.1.0 add button input label card separator
    • If shadcn/ui NOT detected → init first: npx shadcn@2.1.0 init -d (do NOT use shadcn@2 or shadcn@latest — they fail with Tailwind v3. See pitfall #44)
    • Then add needed components: npx shadcn@2.1.0 add button input label card separator
    • Apply theme preset (Scenario C only): After shadcn init, overwrite globals.css with the AI-selected theme:
      • Ocean: Copy skills/auth-setup/assets/themes/ocean.css → src/app/globals.css
      • Sunrise: Copy skills/auth-setup/assets/themes/sunrise.css → src/app/globals.css
    • Font setup: Update src/app/layout.tsx:
      • Ocean: import { DM_Sans } from "next/font/google" → const font = DM_Sans({ subsets: ["latin"] })
      • Sunrise: import { Outfit } from "next/font/google" → const font = Outfit({ subsets: ["latin"] })
    • Dark mode (Ocean only): Set <html lang="en" className="dark"> in layout.tsx

2d. Create Config Files

Generate auth configuration files. For Better Auth:

  1. src/db/schema.ts — Copy from skills/auth-setup/assets/db/better-auth-schema.ts
  2. src/lib/db.ts — Copy from skills/auth-setup/assets/db/better-auth-db.ts. MUST import and pass schema to drizzle(client, { schema })
  3. src/lib/auth.ts — Copy from skills/auth-setup/assets/config/better-auth.config.ts. MUST pass schema to drizzleAdapter: drizzleAdapter(db, { provider: "sqlite", schema })
  4. src/lib/auth-client.ts — Client setup from guide → "Client Setup" section
  5. If email = Resend: Create src/lib/email.ts with sendAuthEmail helper from guide → "Email Provider — Resend" section

CRITICAL for Better Auth callbacks: Use explicit type annotations:

sendVerificationEmail: async ({ user, url }: { user: { email: string }; url: string }) => { ... }
sendResetPassword: async ({ user, url }: { user: { email: string }; url: string }) => { ... }

CRITICAL for Better Auth client: Use requestPasswordReset (NOT forgetPassword — the API was renamed). See pitfall #38.

2e. Set Up Environment Variables

Create .env.example with all required variables. Copy to .env.local.

  • For Better Auth, include: BETTER_AUTH_SECRET, BETTER_AUTH_URL, DATABASE_URL
  • If email = Resend, include: RESEND_API_KEY
  • If OAuth selected, include provider client ID/secret vars

2f. Generate Database Schema

For Better Auth with Drizzle:

  1. Copy schema from assets/db/better-auth-schema.ts
  2. Run npx drizzle-kit push (SQLite) or npx drizzle-kit push:pg (Postgres)
  3. If CLI fails, use the SQL from the schema file directly

2g. Create API Routes

Set up the auth API handler. For Better Auth:

// src/app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);

2h. Add Middleware

For Better Auth: Use cookie-based middleware (NOT auth() wrapper — that's Auth.js, not Better Auth; see pitfall #43):

// src/middleware.ts
import { NextResponse, type NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const sessionCookie =
    request.cookies.get("better-auth.session_token") ||
    request.cookies.get("__Secure-better-auth.session_token");
  const isLoggedIn = !!sessionCookie?.value;
  // ... route protection logic
}

2i. Update next.config

For Better Auth with SQLite/better-sqlite3:

  • Next.js 14: experimental: { serverComponentsExternalPackages: ["better-sqlite3"] }
  • Next.js 15+: serverExternalPackages: ["better-sqlite3"]

Check the Next.js version in package.json FIRST. See pitfall #42.

2j. Add OAuth Providers

If user selected OAuth providers, reference skills/auth-setup/references/07-oauth-social-login.md.

2k. Create UI Components

Check Step 0 existing pages list first:

  • If Step 0 detected existing auth pages (login/, register/, etc.) → warn user before overwriting: "Found existing {page}. Overwrite with plugin component, or skip?"
  • If Step 0 detected existing middleware → warn: "Found existing middleware.ts. I'll merge auth routes into it instead of replacing."

Copy and adapt components from skills/auth-setup/assets/components/:

  • login-page.tsx
  • register-page.tsx
  • forgot-password.tsx
  • reset-password.tsx ← REQUIRED for Better Auth/Auth.js/Supabase
  • protected-layout.tsx
  • dashboard-page.tsx
  • dashboard-client.tsx
  • icons.tsx ← REQUIRED — OAuth provider icons (from shared/)

CRITICAL: You MUST uncomment exactly ONE provider's code in each component. All provider code is commented out by default — leaving it commented means buttons/forms do nothing.

CRITICAL: reset-password.tsx includes a <Suspense> wrapper — do NOT remove it. useSearchParams() requires Suspense in Next.js 14+ or the build fails. See pitfall #39.

CRITICAL for Better Auth: The forgot-password component must use authClient.requestPasswordReset() (NOT forgetPassword). See pitfall #38.

CRITICAL for Firebase Auth: The session cookie MUST be created BEFORE redirecting:

  • Add createSessionCookie() helper from assets/config/firebase.config.ts
  • In login/register: await createSessionCookie(result.user) THEN router.push("/dashboard")

2l. Create Protected Layout

Add server-side session verification at src/app/(protected)/layout.tsx.

2m. Generate README (CRITICAL — do not skip, even after compaction)

This is the final user-facing artifact. Even if context is limited, this MUST run.

Follow SKILL.md Step 8 exactly:

  1. Step 8a — Detect existing README.md. If present, call AskUserQuestion (append / overwrite-with-backup / separate file).
  2. Step 8b — Read the provider's assets/templates/providers/{better-auth,firebase}/README.md.tmpl and substitute {{PLACEHOLDERS}} using the fallback chain in SKILL.md.
  3. Step 8c — Process <!-- IF key=value --> conditional blocks based on user's Step 1a (OAuth) and Step 3 (email) answers. Delete blocks that don't match; remove the marker comments.
  4. Step 8d — Run the verification checklist (no raw {{, no <!-- IF, env vars match .env.example, at least one provider console link, no orphan intra-doc links).

If any verification check fails, re-run the substitution. Do NOT report setup as complete until README is generated and verified.

Step 3: Verify

After setup is complete:

  1. Run npm run build — must succeed with zero errors
  2. Check that all config files exist and are valid
  3. Verify env vars are in .env.example
  4. Confirm API routes are mounted
  5. Confirm middleware is configured
  6. Check that ALL UI components are in place (including reset-password.tsx)

Step 4: Summary

Print a clear summary:

✅ Auth Setup Complete

Provider: [chosen provider]
OAuth: [Google, GitHub, ...]
Database: [Drizzle/Prisma/...]
Email: [Resend/Console/Other]

Files created:
- src/lib/auth.ts
- src/lib/auth-client.ts
- src/lib/db.ts + src/db/schema.ts
- src/lib/email.ts (if Resend)
- src/app/api/auth/[...all]/route.ts
- src/middleware.ts
- src/app/(auth)/login/page.tsx
- src/app/(auth)/register/page.tsx
- src/app/(auth)/forgot-password/page.tsx
- src/app/(auth)/reset-password/page.tsx
- src/app/(protected)/layout.tsx
- src/app/(protected)/dashboard/page.tsx
- .env.example + .env.local

Next steps:
1. Fill in .env.local with your actual API keys
2. Start dev server: npm run dev
3. Test the full flow:
   a. Visit /register → create account → should redirect to /dashboard
   b. Click sign out → should redirect to /login
   c. Visit /login → sign in → should redirect to /dashboard
   d. Visit /forgot-password → enter email → check terminal for reset link
   e. Click the reset link → set new password → should redirect to /login

⚠️ Review references/09-common-pitfalls.md for 60 production pitfalls

Sponsors

Details

Marketplace
ShipWithAI/shipwithai-plugins
Source
plugins/auth
Author
ShipWithAI
Category
Productivity

More from ShipWithAI/shipwithai-plugins

All 7