{
  "id": "add-better-auth-to-nextjs",
  "type": "prompts",
  "category": "prompts",
  "locale": "en",
  "url": "/prompts/add-better-auth-to-nextjs",
  "title": "Prompt to Add Better Auth to Next.js with PostgreSQL",
  "description": "A copy-paste prompt for adding Better Auth and PostgreSQL session handling to a Next.js App Router project.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex"
  ],
  "stack": [
    "Next.js",
    "PostgreSQL",
    "TypeScript"
  ],
  "tags": [
    "auth",
    "nextjs",
    "postgres"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Give this to your agent to wire up email + session auth in a Next.js App Router\nproject without it inventing routes or reaching for an outdated library.\n\n## Main Prompt\n\n```txt title=\"Main Prompt\"\nYou are working in a Next.js App Router project that uses TypeScript and PostgreSQL.\n\nTask: add authentication using Better Auth.\n\nRequirements:\n- Use the `better-auth` package. Do NOT use next-auth/auth.js.\n- Configure email + password auth with database-backed sessions.\n- Use the existing PostgreSQL connection; create the auth tables via Better Auth's schema.\n- Add a server-side `auth` instance in `src/lib/auth.ts`.\n- Mount the handler at `app/api/auth/[...all]/route.ts`.\n- Add a typed `getSession()` helper for Server Components.\n- Do not touch unrelated files. Show me the diff before applying.\n\nStop after the code changes and list exactly which files you created or edited.\n```\n\n## Implementation Notes\n\n- Better Auth ships its own schema; let it generate the tables instead of\n  hand-writing migrations.\n- Keep all secrets in `.env` and validate them at startup.\n- Sessions should be database-backed, not JWT, for easy revocation.\n\n## Expected File Changes\n\n```txt\nsrc/lib/auth.ts                      (new)\napp/api/auth/[...all]/route.ts       (new)\nsrc/lib/get-session.ts               (new)\n.env.example                         (edited)\npackage.json                         (edited)\n```\n\n## Acceptance Criteria\n\n- A new user can sign up and a session row is written to PostgreSQL.\n- `getSession()` returns the user in a Server Component.\n- Signing out clears the session server-side.\n\n## Test Commands\n\n```bash\nbun run typecheck\nbun run dev\n# then exercise /api/auth/sign-up and /api/auth/sign-in\n```\n\n## Common AI Mistakes\n\n- Reaching for `next-auth` even though the prompt forbids it.\n- Storing sessions as JWTs and skipping the database tables.\n- Forgetting to validate `BETTER_AUTH_SECRET` / `DATABASE_URL`.\n\n## Fix Prompt\n\n```txt title=\"Fix Prompt\"\nYou used a different auth library or JWT sessions. Redo it with `better-auth`\nand database-backed sessions only. Remove any next-auth code you added.\n```"
}