{
  "id": "add-better-auth-to-a-nextjs-app",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "en",
  "url": "/playbooks/add-better-auth-to-a-nextjs-app",
  "title": "Prompt-to-PR: Add Better Auth to a Next.js App",
  "description": "Full SOP for wiring Better Auth into a Next.js App Router project — sessions, email/password, OAuth, and middleware protection in one pass.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "TypeScript",
    "PostgreSQL"
  ],
  "tags": [
    "auth",
    "nextjs",
    "typescript",
    "postgres"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "A complete playbook for adding [Better Auth](https://www.better-auth.com/) to an existing Next.js 15 App Router project backed by PostgreSQL. Covers the auth server, route handler, client helper, middleware, and sign-in UI in a single agent run.\n\n## 1. Requirement\n\nAdd session-based authentication with email/password and GitHub OAuth. Protect all routes under `/dashboard` via Next.js middleware. Store sessions in the existing PostgreSQL database using Better Auth's built-in Drizzle adapter.\n\n## 2. First Prompt\n\n```txt title=\"First Prompt\"\nAdd Better Auth to this Next.js 15 App Router project.\n\nStack: PostgreSQL (Drizzle ORM, schema in src/db/schema.ts), TypeScript, Tailwind.\n\nTasks:\n1. Install `better-auth` and `@better-auth/drizzle`.\n2. Create `src/lib/auth.ts` — configure BetterAuth with the Drizzle adapter,\n   emailAndPassword plugin, and GitHub socialProvider. Read secrets from\n   BETTER_AUTH_SECRET, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET env vars.\n3. Create `src/app/api/auth/[...all]/route.ts` that re-exports the auth handler\n   for GET and POST.\n4. Create `src/lib/auth-client.ts` that exports a `createAuthClient()` instance\n   for client components.\n5. Add Better Auth tables to `src/db/schema.ts` using `auth.api.generateSchema()`.\n6. Create `src/middleware.ts` that protects every route under `/dashboard`;\n   redirect unauthenticated requests to `/sign-in`.\n7. Create `src/app/(auth)/sign-in/page.tsx` — a minimal email/password form and\n   a \"Continue with GitHub\" button using the auth client.\n8. Do not touch any existing route or component unless strictly necessary.\n```\n\n## 3. Expected File Changes\n\n```txt\npackage.json                              (better-auth, @better-auth/drizzle)\nsrc/lib/auth.ts                           (new — server auth instance)\nsrc/lib/auth-client.ts                    (new — browser auth client)\nsrc/app/api/auth/[...all]/route.ts        (new — catch-all route handler)\nsrc/db/schema.ts                          (new tables: user, session, account, verification)\nsrc/middleware.ts                         (new — route protection)\nsrc/app/(auth)/sign-in/page.tsx           (new — sign-in UI)\n.env.local.example                        (BETTER_AUTH_SECRET, GITHUB_* vars)\n```\n\n## 4. Review Checklist\n\n- `BETTER_AUTH_SECRET` is at least 32 random bytes — never hardcoded.\n- The catch-all route handler exports both `GET` and `POST`.\n- `src/middleware.ts` uses `matcher` to skip `_next/static`, `_next/image`, and `/api/auth`.\n- The Drizzle adapter receives the same `db` instance used elsewhere — no second connection.\n- `createAuthClient()` in `auth-client.ts` points to the correct `baseURL` (reads `NEXT_PUBLIC_APP_URL`).\n- Sign-in page is a Client Component (`\"use client\"`) — no server-only imports.\n- GitHub OAuth callback URL in the GitHub app settings matches `/api/auth/callback/github`.\n- New schema tables are added, not replacing, existing tables.\n\n## 5. Test Commands\n\n```bash\n# Generate and run the new auth migrations\nnpx drizzle-kit generate\nnpx drizzle-kit migrate\n\n# Start dev server\nbun dev\n\n# Smoke-test: attempt to hit protected route without a session\ncurl -I http://localhost:3000/dashboard\n# Expect: 307 redirect to /sign-in\n\n# Run any existing test suite\nbun test\n```\n\n## 6. Common Failures\n\n- **`BETTER_AUTH_SECRET` missing at runtime** — Better Auth throws on startup. Add it to `.env.local`; confirm with `console.log(process.env.BETTER_AUTH_SECRET?.length)` in `auth.ts` (remove after).\n- **Double Drizzle connection** — agent creates a second `drizzle()` call inside `auth.ts` instead of importing from `src/db/index.ts`. Causes two connection pools.\n- **Middleware matches `/api/auth`** — causes infinite redirect loop. The `matcher` must exclude `/api/auth/(.*)`.\n- **Client component imports server-only `auth`** — build error. Only `auth-client.ts` should be imported in Client Components.\n- **GitHub callback URL mismatch** — OAuth fails silently. Confirm the GitHub OAuth app callback is `http://localhost:3000/api/auth/callback/github` in dev.\n\n## 7. Fix Prompt\n\n```txt title=\"Fix Prompt\"\nThe middleware is redirecting /api/auth/* to /sign-in, causing an infinite loop.\n\nFix src/middleware.ts so the matcher explicitly excludes:\n- /api/auth/:path*\n- /_next/static/:path*\n- /_next/image\n- /favicon.ico\n\nAlso confirm that auth.ts imports `db` from `src/db/index.ts` rather than\ncreating a second Drizzle instance.\n```\n\n## 8. PR Description\n\n```md title=\"PR description\"\n## Auth: Add Better Auth (email/password + GitHub OAuth)\n\n- Installs `better-auth` with Drizzle adapter against the existing PostgreSQL db\n- Catch-all `/api/auth/[...all]` route handles all auth requests\n- Middleware protects `/dashboard/**`; unauthenticated → `/sign-in`\n- New sign-in page with email/password form and GitHub OAuth button\n- Four new schema tables (`user`, `session`, `account`, `verification`) via migration\n\n**Env vars required** (see `.env.local.example`):\n- `BETTER_AUTH_SECRET` — min 32-byte random string\n- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`\n- `NEXT_PUBLIC_APP_URL`\n```"
}