{
  "id": "add-better-auth-to-nextjs",
  "type": "prompts",
  "category": "prompts",
  "locale": "zh",
  "url": "/zh/prompts/add-better-auth-to-nextjs",
  "title": "向 Next.js 与 PostgreSQL 添加 Better Auth 的提示",
  "description": "一个可复制粘贴的提示，用于为 Next.js App Router 项目添加 Better Auth 和 PostgreSQL 会话处理。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex"
  ],
  "stack": [
    "Next.js",
    "PostgreSQL",
    "TypeScript"
  ],
  "tags": [
    "auth",
    "nextjs",
    "postgres"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "将此提示交给你的代理，以便在 Next.js App Router 项目中设置电子邮件 + 会话认证，\n而无需代理自行创建路由或使用过时的库。\n\n## 主提示\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## 实现说明\n\n- Better Auth 自带架构；让它生成表，而不是手动编写迁移。\n- 将所有密钥保存在 `.env` 中，并在启动时验证。\n- 会话应基于数据库而非 JWT，以便轻松撤销。\n\n## 预期的文件变更\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## 验收标准\n\n- 新用户可以注册，并在 PostgreSQL 中写入一行会话数据。\n- `getSession()` 在服务器组件中返回用户。\n- 登出会在服务器端清除会话。\n\n## 测试命令\n\n```bash\nbun run typecheck\nbun run dev\n# then exercise /api/auth/sign-up and /api/auth/sign-in\n```\n\n## 常见 AI 错误\n\n- 即便提示禁止，仍然使用 `next-auth`。\n- 将会话存储为 JWT 并跳过数据库表。\n- 忘记验证 `BETTER_AUTH_SECRET` / `DATABASE_URL`。\n\n## 修复提示\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```"
}