向 Next.js 与 PostgreSQL 添加 Better Auth 的提示
一个可复制粘贴的提示,用于为 Next.js App Router 项目添加 Better Auth 和 PostgreSQL 会话处理。
CursorClaude CodeCodex Next.jsPostgreSQLTypeScript
将此提示交给你的代理,以便在 Next.js App Router 项目中设置电子邮件 + 会话认证, 而无需代理自行创建路由或使用过时的库。
主提示
You are working in a Next.js App Router project that uses TypeScript and PostgreSQL.
Task: add authentication using Better Auth.
Requirements:- Use the `better-auth` package. Do NOT use next-auth/auth.js.- Configure email + password auth with database-backed sessions.- Use the existing PostgreSQL connection; create the auth tables via Better Auth's schema.- Add a server-side `auth` instance in `src/lib/auth.ts`.- Mount the handler at `app/api/auth/[...all]/route.ts`.- Add a typed `getSession()` helper for Server Components.- Do not touch unrelated files. Show me the diff before applying.
Stop after the code changes and list exactly which files you created or edited.实现说明
- Better Auth 自带架构;让它生成表,而不是手动编写迁移。
- 将所有密钥保存在
.env中,并在启动时验证。 - 会话应基于数据库而非 JWT,以便轻松撤销。
预期的文件变更
src/lib/auth.ts (new)app/api/auth/[...all]/route.ts (new)src/lib/get-session.ts (new).env.example (edited)package.json (edited)验收标准
- 新用户可以注册,并在 PostgreSQL 中写入一行会话数据。
getSession()在服务器组件中返回用户。- 登出会在服务器端清除会话。
测试命令
bun run typecheckbun run dev# then exercise /api/auth/sign-up and /api/auth/sign-in常见 AI 错误
- 即便提示禁止,仍然使用
next-auth。 - 将会话存储为 JWT 并跳过数据库表。
- 忘记验证
BETTER_AUTH_SECRET/DATABASE_URL。
修复提示
You used a different auth library or JWT sessions. Redo it with `better-auth`and database-backed sessions only. Remove any next-auth code you added.