
shipwithai-auth
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@shipwithaiRun it inside Claude Code after adding the marketplace with /plugin marketplace add ShipWithAI/shipwithai-plugins.
Contents
Discovered from sourceSkills 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 frompackage.json)- App Router vs Pages Router
- React version, Node.js version
1b. Auth Provider (same as setup Step 0d):
better-authin deps → Better Authfirebasein deps → Firebase@clerk/nextjs,next-auth,@supabase/ssr→ respective provider- If no auth detected → ❌ STOP: "No auth setup detected. Run
/shipwithai-auth:setupfirst."
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.localor.env→ configured env vars- OAuth providers: check env vars for
GOOGLE_CLIENT_ID,GITHUB_CLIENT_ID,APPLE_CLIENT_ID - Email: check for
resendin deps orRESEND_API_KEYin 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.envas fallback)
Check provider-specific required vars:
| Provider | Required |
|---|---|
| Better Auth | BETTER_AUTH_SECRET, BETTER_AUTH_URL |
| Firebase | NEXT_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 fromopenssl rand -hex 32)BETTER_AUTH_URL— must start withhttp://orhttps://NEXT_PUBLIC_FIREBASE_API_KEY— must start withAIzaFIREBASE_PRIVATE_KEY— must contain-----BEGIN
Check for test keys in production:
- ⚠️ WARNING if
BETTER_AUTH_URL=http://localhostin a project withNODE_ENV=productionindicators - ⚠️ WARNING if
RESEND_API_KEY=re_test_(test key can't send to real emails)
Check OAuth var pairs:
- If
GOOGLE_CLIENT_IDexists →GOOGLE_CLIENT_SECRETmust also exist (and vice versa) - If
GITHUB_CLIENT_IDexists →GITHUB_CLIENT_SECRETmust also exist - If
APPLE_CLIENT_IDexists →APPLE_CLIENT_SECRETmust also exist - ❌ CRITICAL if one exists without the other
Check email vars (if Resend detected):
RESEND_API_KEY— must start withre_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.jsondependencies + devDependencies - Verify provider package exists and check version compatibility
Check for known breaking versions:
better-auth< 0.4.0 — major API changesdrizzle-kitwithdriverfield instead ofdialect— deprecated in 0.21+shadcn> 2.1.0 with Tailwind v3 — incompatible (pitfall #44)next>= 16 withmiddleware.ts— deprecated in favor ofproxy.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:
.envand.env.localmust be listedsqlite.dbshould be listed (if SQLite)- ❌ CRITICAL if
.envnot in.gitignore
Scan for hardcoded secrets in source files:
- Scan
src/for patterns:sk_live_,sk_test_,re_,AIza,-----BEGIN,whsec_ - Exclude
.env*files andnode_modules/ - ❌ CRITICAL if found in
.ts/.tsxsource 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.tsfornew Resend(at module scope (outside functions) - Scan
src/lib/auth.tsfornew Stripe(ornew 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.tsforexport { auth as middleware }orexport default auth( - ❌ CRITICAL —
auth()is Auth.js (NextAuth v5), not Better Auth
R5 — Firebase middleware decoding JWT:
- Scan
src/middleware.tsforatob(,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.pushwithout precedingawait 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.tsxforuseSearchParams()without<Suspense> - ❌ CRITICAL —
next buildfails in Next.js 14+
R8 — Missing files from checklist:
- Already covered in Category 2, but double-check
auth-client.tsspecifically - ❌ CRITICAL — cascading import errors
Category 6: Middleware (middleware)
Check middleware exists:
- Look for
src/middleware.tsormiddleware.ts - ⚠️ WARNING if missing
Check middleware pattern matches provider:
| Provider | Correct pattern | Wrong pattern |
|---|---|---|
| Better Auth | request.cookies.get("better-auth.session_token") | auth(), getSession(), headers() |
| Firebase | request.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()fromnext/headersis 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:
socialProvidersinsrc/lib/auth.tsshould 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"(NOTdriver: "better-sqlite") - ❌ CRITICAL if uses deprecated
driverfield
Check schema has auth tables:
- Read
src/db/schema.ts - Must contain:
user,session,account,verificationtables - ❌ 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.dbdoesn't exist — needsnpx drizzle-kit pushto 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:
- ❌ CRITICAL items first (will break at runtime)
- ⚠️ WARNING items second (works but risky)
- ✅ 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.localvalues 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 situation | Best choice | Why |
|---|---|---|
| Full control, no vendor lock-in | Better Auth | Open-source, self-hosted, most flexible, zero cost |
| Google ecosystem or mobile + web | Firebase Auth | Best 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.jsonand extract versions:next— check major version (14, 15, 16+)react— must be ≥18 for Server Componentsnode— checkenginesfield or.nvmrcif 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.tsis deprecated — plugin will useproxy.tspattern instead." - Store version for later decisions:
- Next.js 14 →
experimental: { serverComponentsExternalPackages: [...] } - Next.js 15+ →
serverExternalPackages: [...]
- Next.js 14 →
0c. Database ORM:
- Check
drizzle.config.tsordrizzle.config.js→ Drizzle - Check
prisma/schema.prisma→ Prisma - Fallback: check
package.jsonfordrizzle-ormor@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-authin deps → Better Auth already installed - Check
src/lib/firebase.ts+firebasein deps → Firebase already installed - Check
@clerk/nextjsin deps → Clerk detected - Check
next-authin deps → Auth.js/NextAuth detected - Check
@supabase/ssrin deps → Supabase Auth detected - If auth detected → ⚠️ WARNING: "Existing auth setup detected ({provider}). Running setup may conflict. Run
/shipwithai-auth:doctorfirst 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→ pnpmyarn.lock→ yarnbun.lockb→ bunpackage-lock.json→ npm- Default to npm if no lockfile found
0g. UI Library:
- Check
components.json→ shadcn/ui (readstyleandbaseColorfields) - Check
@mui/materialin deps → MUI - Check
@chakra-ui/reactin deps → Chakra UI - Check
@mantine/corein deps → Mantine - Check for Tailwind:
tailwind.config.*ortailwindcssin deps - If shadcn/ui detected → skip
shadcn initin 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.cssalready 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:
- 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
- Supabase Auth — ⚠️ Coming Soon
- 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:
- Google only (Recommended) — Most common, covers 90%+ of users
- 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: 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:
| Scenario | Condition | globals.css Action |
|---|---|---|
| A | Existing project with shadcn/ui (detected in 0g) | SKIP — use existing CSS variables |
| B | Existing project with Tailwind but no shadcn/ui (detected in 0g) | MERGE — add shadcn/ui vars to existing globals.css |
| C | Standalone new project (no parent design system) | AUTO-SELECT — AI picks Ocean or Sunrise preset |
| D | New project inside/alongside existing project | INHERIT — map parent's design tokens to shadcn/ui vars |
Auto-classification from Step 0:
- If Step 0 detected shadcn/ui (
components.jsonexists) → 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:
| Theme | File | Font | Best for |
|---|---|---|---|
| Ocean | assets/themes/ocean.css | DM Sans | SaaS, dashboard, dev tools, API, analytics, admin, B2B |
| Sunrise | assets/themes/sunrise.css | Outfit | Consumer, blog, shop, community, education, portfolio, e-commerce |
Auto-selection logic (SILENT — no user interaction):
- Read
package.json→nameanddescriptionfields - Read
README.mdfirst paragraph (if exists) - 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
- If ambiguous or no signals → Ocean (default)
After selecting theme:
- Run
npx shadcn@2.1.0 init -dfirst (creates default globals.css) - Overwrite
globals.csswith the selected theme preset file - 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');
- Ocean:
- Update
layout.tsxto 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"] })
- Ocean:
- Ocean is dark-first → set
<html className="dark">inlayout.tsx - 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 -dFIRST, then apply the inherited theme.shadcn initoverwritesglobals.csswith 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
shadcnMappingwithdarkandlightmode values - After shadcn init completes, overwrite
globals.csswith the inherited theme mapping - Add the parent's Google Fonts
@importto globals.css - Set
className="dark"on<html>if the parent is dark-first - Update
layout.tsxto 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
| Provider | Guide |
|---|---|
| Better Auth | references/02-better-auth-guide.md |
| Firebase Auth | references/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):
- Install:
{pm} install resend(use package manager detected in Step 0) - Add to
.env.local:RESEND_API_KEY=re_xxxxxandEMAIL_FROM=onboarding@resend.dev - Create
src/lib/email.tswith thesendAuthEmailhelper from the Better Auth guide → "Email Provider — Resend" section - Update
sendVerificationEmailandsendResetPasswordcallbacks insrc/lib/auth.tsto usesendAuthEmail - IMPORTANT — Tell the user after setup:
"With Resend's free tier and
onboarding@resend.devas 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 changeEMAIL_FROMtoauth@yourdomain.com."
If B (Console):
- Keep the
console.logstubs in auth config (already the default) - Tell user: "Check your terminal for verification/reset links during development"
If C (Other):
- Keep the
console.logstubs as placeholder - 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 runnpx shadcn@2.1.0 add button input label card separatorfor missing components - If shadcn/ui NOT detected → run
npx shadcn@2.1.0 init -dfirst, 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):
| File | Source folder | Place at | Purpose |
|---|---|---|---|
login-page.tsx | {provider}/ | app/(auth)/login/page.tsx | Login with email + social buttons |
register-page.tsx | {provider}/ | app/(auth)/register/page.tsx | Registration form |
forgot-password.tsx | {provider}/ | app/(auth)/forgot-password/page.tsx | Password reset request (sends email) |
reset-password.tsx | {provider}/ | app/(auth)/reset-password/page.tsx | Complete password reset (token from email → new password) |
protected-layout.tsx | {provider}/ | app/(protected)/layout.tsx | Server-side session verification |
dashboard-client.tsx | {provider}/ | app/(protected)/dashboard/dashboard-client.tsx | Sign-out button (client component) |
dashboard-page.tsx | shared/ | app/(protected)/dashboard/page.tsx | Protected dashboard page |
icons.tsx | shared/ | src/components/icons.tsx | OAuth provider SVG icons (Google, GitHub) — required by login/register pages |
globals.css | shared/ | app/globals.css | Tailwind CSS directives + shadcn/ui variables |
RECOMMENDED — User management (copy unless user explicitly declines):
| File | Source folder | Place at | Purpose |
|---|---|---|---|
user-profile.tsx | {provider}/ | app/(protected)/profile/page.tsx | Profile 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 configdrizzle.config.ts— Drizzle Kit config withdialect: "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:
src/lib/firebase.ts— Client SDK init (fromfirebase.config.ts→ "Client SDK Setup")src/lib/firebase-admin.ts— Admin SDK init (fromfirebase.config.ts→ "Admin SDK Setup")src/lib/firebase-session.ts—createSessionCookie()+clearSessionAndSignOut()helpers (fromfirebase.config.ts→ "Session Cookie Helper" + "Sign-Out Helper")src/lib/auth-server.ts—getServerUser()helper (fromfirebase.config.ts→ "Server Component Auth Check"). Import this in BOTH(protected)/layout.tsxAND(protected)/dashboard/page.tsx— do NOT duplicate the function inlinesrc/app/api/auth/session/route.ts— Session API with rate limiting + CSRF (fromfirebase.config.ts→ "Session Cookie API Route"). The POST handler MUST be wrapped in try/catch — return 401 on invalid token, never 500src/middleware.ts— Route protection (fromassets/middleware/firebase/nextjs-middleware.ts)app/globals.css— Tailwind v3 directives (@tailwind base; @tailwind components; @tailwind utilities;) + shadcn/ui hsl CSS variables —layout.tsximports this file. Copy fromassets/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:
- Enable Google provider in Firebase Console (not just Google Cloud Console)
- Configure the correct OAuth client ID in Google Cloud Console (must match Firebase's Web client ID)
- Add
https://<PROJECT>.firebaseapp.com/__/auth/handlerto Authorized redirect URIs (NOT/api/auth/callback/google— that's Auth.js) - 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:
- After sign-in/register, call
createSessionCookie(result.user)and await it - Only THEN redirect to
/dashboard - On sign-out, call
clearSessionAndSignOut()FIRST (clears server cookie + Firebase), then redirect - Never rely on
onAuthStateChangedfor the initial login redirect
CRITICAL for Firebase Auth Security:
- Set
NEXT_PUBLIC_APP_URLenv var — required for CSRF protection on session endpoint - Place protected pages under
app/(protected)/and useprotected-layout.tsxto verify sessions server-side (middleware only checks cookie existence, NOT validity) - The session DELETE handler revokes Firebase refresh tokens — stolen sessions are invalidated immediately
- 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:
src/db/schema.ts— Drizzle schema with Better Auth tables (fromassets/db/better-auth-schema.ts)src/lib/db.ts— Drizzle client (fromassets/db/better-auth-db.ts). MUST import and passschematodrizzle(client, { schema })src/lib/auth.ts— Server config (fromassets/config/better-auth.config.ts). MUST passschemato drizzleAdapter:drizzleAdapter(db, { provider: "sqlite", schema })src/lib/auth-client.ts— Client setup (frombetter-auth.config.ts→ "Client Setup" section)src/app/api/auth/[...all]/route.ts— API route handlersrc/middleware.ts— Route protection using cookie-based pattern (fromassets/middleware/better-auth/nextjs-middleware.ts). Do NOT useauth()wrapper — that's Auth.js, not Better Auth (see pitfall #43)src/app/(protected)/layout.tsx— Server-side session verification.env.local— Copy fromassets/config/better-auth.env.exampleand fill in valuesdrizzle.config.ts— Copy fromassets/config/drizzle.config.ts. MUST usedialect: "sqlite"(NOTdriver: "better-sqlite"— removed in drizzle-kit 0.21+). See pitfall #48.- Database migration — Create tables with
npx drizzle-kit push(ornpx @better-auth/cli generate && npx @better-auth/cli migrate) - UI components — Copy login, register, forgot-password, reset-password, dashboard from
assets/components/better-auth/(shared components fromassets/components/shared/) reset-password.tsxalready includes a<Suspense>wrapper —useSearchParams()requires this in Next.js 14+ App Router or the build fails. Do NOT remove the Suspense wrapper.- shadcn/ui: Use
npx shadcn@2.1.0(NOT@latestor@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 inpackage.jsonBEFORE writing the config. Using the wrong syntax causes:Unrecognized key(s) in object: 'serverExternalPackages'.
CRITICAL for Better Auth — Session flow:
- Better Auth manages sessions via cookies (
better-auth.session_token) — no manual cookie creation needed (unlike Firebase) cookieCacheis enabled by default (5 min) — session changes (role updates, email verification) take up to 5 minutes to propagate- In Server Components, use
auth.api.getSession({ headers: await headers() })— this verifies the session cryptographically - In middleware, check the
better-auth.session_tokencookie directly — do NOT useauth()wrapper (that's Auth.js, see pitfall #43). Do NOT useheaders()fromnext/headersin 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):
- Check existence FIRST. Use
Globwith patternREADME.md(orBash: ls README.md 2>/dev/null) to detect. - If README.md does NOT exist → skip to Step 8b, proceed with
Writedirectly. - If README.md EXISTS:
a. Read it first (
Read README.md) — required before any laterWriteto that path AND so you can summarize current content to the user. b. CallAskUserQuestionwith 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.bakviaBash: cp README.md README.md.bak, thenWritenew README) - C) Save separately as
README.AUTH.md(Writeto 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
Editto append the rendered template under a new## Authenticationsection. Do NOT useWrite(it would overwrite). - B (Overwrite): Run backup
Bashcommand first → verify.bakexists → thenWriteREADME.md with new content. - C (Separate):
WritetoREADME.AUTH.mdinstead ofREADME.md. Mention the new file in the final summary.
- A) Append AUTH section (default — preserves existing content, adds auth docs at the end via
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}}):
| Placeholder | Source | Fallback chain |
|---|---|---|
{{PROJECT_NAME}} | package.json name | 1) strip @scope/ → 2) basename(cwd) → 3) My App |
{{NEXT_VERSION}} | Step 0b | 14+ if unknown |
{{ORM}} | Step 0c | Drizzle (Better Auth default) |
Provider name is pre-resolved by selecting the correct template file (
firebase/vsbetter-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(useassets/config/next.config.tstemplate) - Add protected layout for server-side session verification (Firebase)
- Set
NEXT_PUBLIC_APP_URLfor CSRF protection (Firebase) - Enable rate limiting for production (see
05-firebase-auth-guide.mdSecurity 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:
- Environment Variables — missing/empty keys, test keys in production, unpaired OAuth secrets
- File Structure — missing required files per provider checklist
- Dependencies — wrong versions, missing packages, peer dep conflicts
- Security — hardcoded secrets, .gitignore gaps, exposed API keys
- Dangerous Code Patterns — module-scope SDK init (R1), wrong middleware (R4/R5), missing Suspense (R7)
- Middleware — wrong pattern for provider, Edge Runtime violations, missing route matcher
- OAuth Configuration — incomplete provider setup, wrong callback URLs, missing redirect URIs
- 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:
- Framework —
next.config.*→ Next.js (check version: 14/15/16+) - Router —
app/→ App Router |pages/→ Pages Router (❌ block if no App Router) - Version compat — React ≥18, Node ≥18. Block if incompatible.
- ORM —
drizzle.config.ts→ Drizzle |prisma/schema.prisma→ Prisma | deps fallback - Existing auth —
better-auth,firebase,@clerk/nextjs,next-auth,@supabase/ssrin deps - Existing pages —
(auth)/login/,api/auth/,middleware.ts,README.mdat project root (used by Step 2m) - Package manager — lockfile detection (pnpm/yarn/bun/npm)
- UI library —
components.json→ shadcn/ui | Tailwind | MUI/Chakra/Mantine - Design system — existing
globals.csswith 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.tsfound). 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.jsonexists) → Scenario A — skip this question entirely - If existing
globals.csshas shadcn CSS vars (:rootwith--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):
| Scenario | Condition | globals.css Action |
|---|---|---|
| A | Existing project with shadcn/ui (detected in Step 0) | SKIP — use existing CSS variables |
| B | Existing project with Tailwind but no shadcn/ui | MERGE — add shadcn/ui vars to existing globals.css |
| C | Standalone new project (no parent design system) | AUTO-SELECT — AI picks Ocean or Sunrise preset |
| D | New project inside/alongside existing project | INHERIT — 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 →(Coming Soon)references/03-clerk-guide.mdAuth.js →(Coming Soon)references/04-authjs-guide.mdSupabase →(Coming Soon)references/06-supabase-auth-guide.md
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.tsinstead ofmiddleware.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 useshadcn@2orshadcn@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, overwriteglobals.csswith 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
- Ocean: Copy
- 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"] })
- Ocean:
- Dark mode (Ocean only): Set
<html lang="en" className="dark">inlayout.tsx
- If shadcn/ui already detected in Step 0 → skip init, only add missing components:
2d. Create Config Files
Generate auth configuration files. For Better Auth:
src/db/schema.ts— Copy fromskills/auth-setup/assets/db/better-auth-schema.tssrc/lib/db.ts— Copy fromskills/auth-setup/assets/db/better-auth-db.ts. MUST import and passschematodrizzle(client, { schema })src/lib/auth.ts— Copy fromskills/auth-setup/assets/config/better-auth.config.ts. MUST passschemato drizzleAdapter:drizzleAdapter(db, { provider: "sqlite", schema })src/lib/auth-client.ts— Client setup from guide → "Client Setup" section- If email = Resend: Create
src/lib/email.tswithsendAuthEmailhelper 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:
- Copy schema from
assets/db/better-auth-schema.ts - Run
npx drizzle-kit push(SQLite) ornpx drizzle-kit push:pg(Postgres) - 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.tsxregister-page.tsxforgot-password.tsxreset-password.tsx← REQUIRED for Better Auth/Auth.js/Supabaseprotected-layout.tsxdashboard-page.tsxdashboard-client.tsxicons.tsx← REQUIRED — OAuth provider icons (fromshared/)
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 fromassets/config/firebase.config.ts - In login/register:
await createSessionCookie(result.user)THENrouter.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:
- Step 8a — Detect existing
README.md. If present, callAskUserQuestion(append / overwrite-with-backup / separate file). - Step 8b — Read the provider's
assets/templates/providers/{better-auth,firebase}/README.md.tmpland substitute{{PLACEHOLDERS}}using the fallback chain in SKILL.md. - 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. - 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:
- Run
npm run build— must succeed with zero errors - Check that all config files exist and are valid
- Verify env vars are in
.env.example - Confirm API routes are mounted
- Confirm middleware is configured
- 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
Hooks 1
Sponsors
Details
- Marketplace
- ShipWithAI/shipwithai-plugins
- Source
- plugins/auth
- Author
- ShipWithAI
- Category
- Productivity