create-auth
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCreate Auth Skill
认证功能搭建指南
Guide for adding authentication to TypeScript/JavaScript applications using Better Auth.
For code examples and syntax, see better-auth.com/docs.
Phase 1: Planning (REQUIRED before implementation)
第一阶段:规划(实施前必须完成)
Before writing any code, gather requirements by scanning the project and asking the user structured questions. This ensures the implementation matches their needs.
在编写任何代码之前,先扫描项目并向用户提出结构化问题以收集需求。这能确保最终实现符合用户需求。
Step 1: Scan the project
步骤1:扫描项目
Analyze the codebase to auto-detect:
- Framework — Look for ,
next.config,svelte.config,nuxt.config,astro.config, or Express/Hono entry files.vite.config - Database/ORM — Look for ,
prisma/schema.prisma,drizzle.config.tsdeps (package.json,pg,postgres,@neondatabase/serverless,mysql2,better-sqlite3,mongoose). Ifmongodbexists, read itsdrizzle.config.tsfield to determine the DB type (e.g.,dialect→ Drizzle + Postgres). Also check which Drizzle driver is installed ("postgresql"→drizzle-orm/node-postgres,pg→drizzle-orm/postgres-js,postgres→ Neon).drizzle-orm/neon-http - Existing auth — Look for existing auth libraries (,
next-auth,lucia,clerk,supabase/auth) infirebase/author imports.package.json - Package manager — Check for ,
pnpm-lock.yaml,yarn.lock, orbun.lockb.package-lock.json
Use what you find to pre-fill defaults and skip questions you can already answer.
分析代码库以自动检测:
- 框架 — 查找、
next.config、svelte.config、nuxt.config、astro.config或Express/Hono入口文件。vite.config - 数据库/ORM — 查找、
prisma/schema.prisma、drizzle.config.ts依赖(package.json、pg、postgres、@neondatabase/serverless、mysql2、better-sqlite3、mongoose)。如果存在mongodb,读取其drizzle.config.ts字段以确定数据库类型(例如dialect→ Drizzle + Postgres)。同时检查安装的Drizzle驱动("postgresql"→drizzle-orm/node-postgres、pg→drizzle-orm/postgres-js、postgres→ Neon)。drizzle-orm/neon-http - 现有认证方案 — 在或导入语句中查找现有认证库(
package.json、next-auth、lucia、clerk、supabase/auth)。firebase/auth - 包管理器 — 检查是否存在、
pnpm-lock.yaml、yarn.lock或bun.lockb。package-lock.json
利用检测到的信息预填默认值,跳过已能确定答案的问题。
Step 2: Ask planning questions
步骤2:提出规划问题
Use the tool to ask the user all applicable questions in a single call. Skip any question you already have a confident answer for from the scan. Group them under a title like "Auth Setup Planning".
AskQuestionQuestions to ask:
-
Project type (skip if detected)
- Prompt: "What type of project is this?"
- Options: New project from scratch | Adding auth to existing project | Migrating from another auth library
-
Framework (skip if detected)
- Prompt: "Which framework are you using?"
- Options: Next.js (App Router) | Next.js (Pages Router) | SvelteKit | Nuxt | Astro | Express | Hono | SolidStart | Other
-
Database & ORM (skip if detected)
- Prompt: "Which database setup will you use?"
- Options: PostgreSQL (Prisma) | PostgreSQL (Drizzle) | PostgreSQL (pg driver) | MySQL (Prisma) | MySQL (Drizzle) | MySQL (mysql2 driver) | SQLite (Prisma) | SQLite (Drizzle) | SQLite (better-sqlite3 driver) | MongoDB (Mongoose) | MongoDB (native driver)
-
Authentication methods (always ask, allow multiple)
- Prompt: "Which sign-in methods do you need?"
- Options: Email & password | Social OAuth (Google, GitHub, etc.) | Magic link (passwordless email) | Passkey (WebAuthn) | Phone number
allow_multiple: true
-
Social providers (only if they selected Social OAuth above — ask in a follow-up call)
- Prompt: "Which social providers do you need?"
- Options: Google | GitHub | Apple | Microsoft | Discord | Twitter/X
allow_multiple: true
-
Email verification (only if Email & password was selected above — ask in a follow-up call)
- Prompt: "Do you want to require email verification?"
- Options: Yes | No
-
Email provider (only if email verification is Yes, or if Password reset is selected in features — ask in a follow-up call)
- Prompt: "How do you want to send emails?"
- Options: Resend | Mock it for now (console.log)
-
Features & plugins (always ask, allow multiple)
- Prompt: "Which additional features do you need?"
- Options: Two-factor authentication (2FA) | Organizations / teams | Admin dashboard | API bearer tokens | Password reset | None of these
allow_multiple: true
-
Auth pages (always ask, allow multiple — pre-select based on earlier answers)
- Prompt: "Which auth pages do you need?"
- Options vary based on previous answers:
- Always available: Sign in | Sign up
- If Email & password selected: Forgot password | Reset password
- If email verification enabled: Email verification
allow_multiple: true
-
Auth UI style (always ask)
- Prompt: "What style do you want for the auth pages? Pick one or describe your own."
- Options: Minimal & clean | Centered card with background | Split layout (form + hero image) | Floating / glassmorphism | Other (I'll describe)
使用工具一次性提出所有适用问题。跳过通过扫描已能确定答案的问题。将问题归类在类似“认证设置规划”的标题下。
AskQuestion需提出的问题:
-
项目类型(若已检测到则跳过)
- 提示:“这是什么类型的项目?”
- 选项:从零开始的新项目 | 为现有项目添加认证 | 从其他认证库迁移
-
框架(若已检测到则跳过)
- 提示:“你使用的是哪种框架?”
- 选项:Next.js(App Router) | Next.js(Pages Router) | SvelteKit | Nuxt | Astro | Express | Hono | SolidStart | 其他
-
数据库与ORM(若已检测到则跳过)
- 提示:“你将使用哪种数据库配置?”
- 选项:PostgreSQL(Prisma) | PostgreSQL(Drizzle) | PostgreSQL(pg驱动) | MySQL(Prisma) | MySQL(Drizzle) | MySQL(mysql2驱动) | SQLite(Prisma) | SQLite(Drizzle) | SQLite(better-sqlite3驱动) | MongoDB(Mongoose) | MongoDB(原生驱动)
-
认证方式(必问,可多选)
- 提示:“你需要哪些登录方式?”
- 选项:邮箱与密码 | 社交OAuth(Google、GitHub等) | 魔法链接(无密码邮箱登录) | Passkey(WebAuthn) | 手机号
allow_multiple: true
-
社交提供商(仅当用户选择了社交OAuth时在后续提问中提出)
- 提示:“你需要哪些社交提供商?”
- 选项:Google | GitHub | Apple | Microsoft | Discord | Twitter/X
allow_multiple: true
-
邮箱验证(仅当用户选择了邮箱与密码时在后续提问中提出)
- 提示:“你是否需要强制邮箱验证?”
- 选项:是 | 否
-
邮箱服务商(仅当邮箱验证选择“是”,或功能中选择了密码重置时在后续提问中提出)
- 提示:“你希望通过什么方式发送邮件?”
- 选项:Resend | 暂时模拟(console.log输出)
-
功能与插件(必问,可多选)
- 提示:“你需要哪些附加功能?”
- 选项:双因素认证(2FA) | 组织/团队 | 管理后台 | API Bearer令牌 | 密码重置 | 以上都不需要
allow_multiple: true
-
认证页面(必问,可多选 — 根据之前的答案预选)
- 提示:“你需要哪些认证页面?”
- 选项根据之前的答案有所不同:
- 始终可选:登录 | 注册
- 若选择了邮箱与密码:忘记密码 | 重置密码
- 若启用了邮箱验证:邮箱验证
allow_multiple: true
-
认证UI风格(必问)
- 提示:“你希望认证页面采用什么风格?选择一个或描述自定义风格。”
- 选项:极简干净 | 带背景的居中卡片 | 分栏布局(表单+英雄图) | 悬浮/玻璃态 | 其他(我将描述)
Step 3: Summarize the plan
步骤3:总结规划方案
After collecting answers, present a concise implementation plan as a markdown checklist. Example:
undefined收集答案后,以Markdown清单形式呈现简洁的实施计划。示例:
undefinedAuth Implementation Plan
认证实施计划
- Framework: Next.js (App Router)
- Database: PostgreSQL via Prisma
- Auth methods: Email/password, Google OAuth, GitHub OAuth
- Plugins: 2FA, Organizations, Email verification
- UI: Custom forms
- 框架: Next.js (App Router)
- 数据库: 通过Prisma连接PostgreSQL
- 认证方式: 邮箱/密码、Google OAuth、GitHub OAuth
- 插件: 2FA、组织、邮箱验证
- UI: 自定义表单
Steps
步骤
- Install and
better-auth@better-auth/cli - Create with server config
lib/auth.ts - Create with React client
lib/auth-client.ts - Set up route handler at
app/api/auth/[...all]/route.ts - Configure Prisma adapter and generate schema
- Add Google & GitHub OAuth providers
- Enable and
twoFactorpluginsorganization - Set up email verification handler
- Run migrations
- Create sign-in / sign-up pages
Ask the user to confirm the plan before proceeding to Phase 2.
---- 安装和
better-auth@better-auth/cli - 创建配置服务端
lib/auth.ts - 创建配置React客户端
lib/auth-client.ts - 在设置路由处理器
app/api/auth/[...all]/route.ts - 配置Prisma适配器并生成Schema
- 添加Google与GitHub OAuth提供商
- 启用和
twoFactor插件organization - 设置邮箱验证处理器
- 运行迁移
- 创建登录/注册页面
在进入第二阶段之前,请用户确认该计划。
---Phase 2: Implementation
第二阶段:实施
Only proceed here after the user confirms the plan from Phase 1.
Follow the decision tree below, guided by the answers collected above.
Is this a new/empty project?
├─ YES → New project setup
│ 1. Install better-auth (+ scoped packages per plan)
│ 2. Create auth.ts with all planned config
│ 3. Create auth-client.ts with framework client
│ 4. Set up route handler
│ 5. Set up environment variables
│ 6. Run CLI migrate/generate
│ 7. Add plugins from plan
│ 8. Create auth UI pages
│
├─ MIGRATING → Migration from existing auth
│ 1. Audit current auth for gaps
│ 2. Plan incremental migration
│ 3. Install better-auth alongside existing auth
│ 4. Migrate routes, then session logic, then UI
│ 5. Remove old auth library
│ 6. See migration guides in docs
│
└─ ADDING → Add auth to existing project
1. Analyze project structure
2. Install better-auth
3. Create auth config matching plan
4. Add route handler
5. Run schema migrations
6. Integrate into existing pages
7. Add planned plugins and featuresAt the end of implementation, guide users thoroughly on remaining next steps (e.g., setting up OAuth app credentials, deploying env vars, testing flows).
仅在用户确认第一阶段的计划后再进行此阶段。
根据收集到的答案,遵循以下决策树操作。
这是新项目/空项目吗?
├─ 是 → 新项目设置
│ 1. 安装better-auth(+ 根据计划安装作用域包)
│ 2. 创建包含所有规划配置的auth.ts
│ 3. 创建适配框架的auth-client.ts
│ 4. 设置路由处理器
│ 5. 设置环境变量
│ 6. 运行CLI的migrate/generate命令
│ 7. 添加计划中的插件
│ 8. 创建认证UI页面
│
├─ 迁移 → 从现有认证方案迁移
│ 1. 审核当前认证方案的不足
│ 2. 规划增量迁移步骤
│ 3. 在现有认证库旁安装better-auth
│ 4. 先迁移路由,再迁移会话逻辑,最后迁移UI
│ 5. 移除旧认证库
│ 6. 查看文档中的迁移指南
│
└─ 添加 → 为现有项目添加认证
1. 分析项目结构
2. 安装better-auth
3. 创建符合规划的认证配置
4. 添加路由处理器
5. 运行Schema迁移
6. 集成到现有页面
7. 添加计划中的插件和功能实施完成后,详细指导用户完成剩余后续步骤(例如设置OAuth应用凭证、部署环境变量、测试流程)。
Installation
安装
Core:
npm install better-authScoped packages (as needed):
| Package | Use case |
|---|---|
| WebAuthn/Passkey auth |
| SAML/OIDC enterprise SSO |
| Stripe payments |
| SCIM user provisioning |
| React Native/Expo |
核心包:
npm install better-auth作用域包(按需安装):
| 包名 | 使用场景 |
|---|---|
| WebAuthn/Passkey认证 |
| SAML/OIDC企业级SSO |
| Stripe支付集成 |
| SCIM用户配置 |
| React Native/Expo适配 |
Environment Variables
环境变量
env
BETTER_AUTH_SECRET=<32+ chars, generate with: openssl rand -base64 32>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<your database connection string>Add OAuth secrets as needed: , , , etc.
GITHUB_CLIENT_IDGITHUB_CLIENT_SECRETGOOGLE_CLIENT_IDenv
BETTER_AUTH_SECRET=<32+字符,可通过以下命令生成:openssl rand -base64 32>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<你的数据库连接字符串>按需添加OAuth密钥:、、等。
GITHUB_CLIENT_IDGITHUB_CLIENT_SECRETGOOGLE_CLIENT_IDServer Config (auth.ts)
服务端配置(auth.ts)
Location: or
lib/auth.tssrc/lib/auth.tsMinimal config needs:
- - Connection or adapter
database - - For email/password auth
emailAndPassword: { enabled: true }
Standard config adds:
- - OAuth providers (google, github, etc.)
socialProviders - - Email verification handler
emailVerification.sendVerificationEmail - - Password reset handler
emailAndPassword.sendResetPassword
Full config adds:
- - Array of feature plugins
plugins - - Expiry, cookie cache settings
session - - Multi-provider linking
account.accountLinking - - Rate limiting config
rateLimit
Export types:
export type Session = typeof auth.$Infer.Session位置: 或
lib/auth.tssrc/lib/auth.ts最小配置要求:
- - 连接或适配器
database - - 用于邮箱/密码认证
emailAndPassword: { enabled: true }
标准配置新增:
- - OAuth提供商(google、github等)
socialProviders - - 邮箱验证处理器
emailVerification.sendVerificationEmail - - 密码重置处理器
emailAndPassword.sendResetPassword
完整配置新增:
- - 功能插件数组
plugins - - 过期时间、Cookie缓存设置
session - - 多提供商账号关联
account.accountLinking - - 限流配置
rateLimit
导出类型:
export type Session = typeof auth.$Infer.SessionClient Config (auth-client.ts)
客户端配置(auth-client.ts)
Import by framework:
| Framework | Import |
|---|---|
| React/Next.js | |
| Vue | |
| Svelte | |
| Solid | |
| Vanilla JS | |
Client plugins go in .
createAuthClient({ plugins: [...] })Common exports: , , , ,
signInsignUpsignOutuseSessiongetSession按框架导入:
| 框架 | 导入路径 |
|---|---|
| React/Next.js | |
| Vue | |
| Svelte | |
| Solid | |
| Vanilla JS | |
客户端插件需添加到中。
createAuthClient({ plugins: [...] })常用导出: 、、、、
signInsignUpsignOutuseSessiongetSessionRoute Handler Setup
路由处理器设置
| Framework | File | Handler |
|---|---|---|
| Next.js App Router | | |
| Next.js Pages | | |
| Express | Any file | |
| SvelteKit | | |
| SolidStart | Route file | |
| Hono | Route file | |
Next.js Server Components: Add plugin to auth config.
nextCookies()| 框架 | 文件路径 | 处理器 |
|---|---|---|
| Next.js App Router | | |
| Next.js Pages | | |
| Express | 任意文件 | |
| SvelteKit | | |
| SolidStart | 路由文件 | |
| Hono | 路由文件 | |
Next.js服务端组件: 在认证配置中添加插件。
nextCookies()Database Migrations
数据库迁移
| Adapter | Command |
|---|---|
| Built-in Kysely | |
| Prisma | |
| Drizzle (dev) | |
| Drizzle (prod) | |
Note:skips migration files and is only safe for development. Usedrizzle-kit push+drizzle-kit generatein production.drizzle-kit migrate
Re-run after adding plugins.
| 适配器 | 命令 |
|---|---|
| 内置Kysely | |
| Prisma | |
| Drizzle(开发环境) | |
| Drizzle(生产环境) | |
注意:会跳过迁移文件,仅在开发环境中使用安全。生产环境请使用drizzle-kit push+drizzle-kit generate。drizzle-kit migrate
添加插件后需重新运行。
Database Adapters
数据库适配器
| Database | Setup |
|---|---|
| SQLite | Pass |
| PostgreSQL | Pass |
| MySQL | Pass |
| Prisma | |
| Drizzle (pg) | |
| Drizzle (mysql) | |
| Drizzle (sqlite) | |
| MongoDB | |
| 数据库 | 设置方式 |
|---|---|
| SQLite | 直接传入 |
| PostgreSQL | 直接传入 |
| MySQL | 直接传入 |
| Prisma | 从 |
| Drizzle(pg) | 从 |
| Drizzle(mysql) | 从 |
| Drizzle(sqlite) | 从 |
| MongoDB | 从 |
Drizzle + PostgreSQL Setup
Drizzle + PostgreSQL 设置
Before using , initialize the instance:
drizzleAdapterdbts
// Option 1: node-postgres (pg)
import { drizzle } from "drizzle-orm/node-postgres"
import { Pool } from "pg"
import * as schema from "./auth-schema"
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
export const db = drizzle(pool, { schema })ts
// Option 2: postgres.js
import { drizzle } from "drizzle-orm/postgres-js"
import postgres from "postgres"
import * as schema from "./auth-schema"
const client = postgres(process.env.DATABASE_URL!)
export const db = drizzle(client, { schema })ts
// Option 3: Neon serverless
import { drizzle } from "drizzle-orm/neon-http"
import { neon } from "@neondatabase/serverless"
import * as schema from "./auth-schema"
const sql = neon(process.env.DATABASE_URL!)
export const db = drizzle(sql, { schema })Then pass to Better Auth:
ts
import { betterAuth } from "better-auth"
import { drizzleAdapter } from "better-auth/adapters/drizzle"
import { db } from "./db"
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "pg" }),
// ...
})使用前,先初始化实例:
drizzleAdapterdbts
// 选项1:node-postgres (pg)
import { drizzle } from "drizzle-orm/node-postgres"
import { Pool } from "pg"
import * as schema from "./auth-schema"
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
export const db = drizzle(pool, { schema })ts
// 选项2:postgres.js
import { drizzle } from "drizzle-orm/postgres-js"
import postgres from "postgres"
import * as schema from "./auth-schema"
const client = postgres(process.env.DATABASE_URL!)
export const db = drizzle(client, { schema })ts
// 选项3:Neon serverless
import { drizzle } from "drizzle-orm/neon-http"
import { neon } from "@neondatabase/serverless"
import * as schema from "./auth-schema"
const sql = neon(process.env.DATABASE_URL!)
export const db = drizzle(sql, { schema })然后传入Better Auth:
ts
import { betterAuth } from "better-auth"
import { drizzleAdapter } from "better-auth/adapters/drizzle"
import { db } from "./db"
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "pg" }),
// ...
})Drizzle Config (drizzle.config.ts
)
drizzle.config.tsDrizzle 配置(drizzle.config.ts
)
drizzle.config.tsRequired for commands to find your schema:
drizzle-kitts
import { defineConfig } from "drizzle-kit"
export default defineConfig({
schema: "./src/db/auth-schema.ts",
out: "./drizzle",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL!,
},
})drizzle-kitts
import { defineConfig } from "drizzle-kit"
export default defineConfig({
schema: "./src/db/auth-schema.ts",
out: "./drizzle",
dialect: "postgresql",
dbCredentials: {
url: process.env.DATABASE_URL!,
},
})Common Plugins
常用插件
| Plugin | Server Import | Client Import | Purpose |
|---|---|---|---|
| | | 2FA with TOTP/OTP |
| | | Teams/orgs |
| | | User management |
| | - | API token auth |
| | - | API docs |
| | | WebAuthn |
| | - | Enterprise SSO |
Plugin pattern: Server plugin + client plugin + run migrations.
| 插件 | 服务端导入路径 | 客户端导入路径 | 用途 |
|---|---|---|---|
| | | 基于TOTP/OTP的双因素认证 |
| | | 团队/组织管理 |
| | | 用户管理 |
| | - | API令牌认证 |
| | - | API文档生成 |
| | | WebAuthn认证 |
| | - | 企业级SSO |
插件使用模式: 服务端插件 + 客户端插件 + 运行迁移。
Auth UI Implementation
认证UI实现
Sign in flow:
- or
signIn.email({ email, password })signIn.social({ provider, callbackURL }) - Handle in response
error - Redirect on success
Session check (client): hook returns
useSession(){ data: session, isPending }Session check (server):
auth.api.getSession({ headers: await headers() })Protected routes: Check session, redirect to if null.
/sign-in登录流程:
- 调用或
signIn.email({ email, password })signIn.social({ provider, callbackURL }) - 处理响应中的
error - 成功后重定向
客户端会话检查: 钩子返回
useSession(){ data: session, isPending }服务端会话检查:
auth.api.getSession({ headers: await headers() })受保护路由: 检查会话,若为空则重定向到。
/sign-inSecurity Checklist
安全检查清单
- set (32+ chars)
BETTER_AUTH_SECRET - in production
advanced.useSecureCookies: true - configured
trustedOrigins - Rate limits enabled
- Email verification enabled
- Password reset implemented
- 2FA for sensitive apps
- CSRF protection NOT disabled
- reviewed
account.accountLinking
- 设置(32+字符)
BETTER_AUTH_SECRET - 生产环境中启用
advanced.useSecureCookies: true - 配置
trustedOrigins - 启用限流
- 启用邮箱验证
- 实现密码重置
- 敏感应用启用2FA
- 未禁用CSRF保护
- 审核设置
account.accountLinking
Troubleshooting
故障排除
| Issue | Fix |
|---|---|
| "Secret not set" | Add |
| "Invalid Origin" | Add domain to |
| Cookies not setting | Check |
| OAuth callback errors | Verify redirect URIs in provider dashboard |
| Type errors after adding plugin | Re-run CLI generate/migrate |
| 问题 | 解决方法 |
|---|---|
| "Secret not set" | 添加 |
| "Invalid Origin" | 将域名添加到 |
| Cookie无法设置 | 检查 |
| OAuth回调错误 | 验证提供商控制台中的重定向URI |
| 添加插件后出现类型错误 | 重新运行CLI的generate/migrate命令 |