better-auth
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBetter Auth
Better Auth
Framework-agnostic TypeScript auth library. Plugin-based architecture, 40+ OAuth providers, 18+ framework integrations.
一款与框架无关的TypeScript认证库。采用插件化架构,支持40+种OAuth服务商、18+种框架集成。
Quick Start
快速开始
Install
安装
bash
npm install better-authScoped packages (as needed):
| Package | Use case |
|---|---|
| WebAuthn/Passkey auth |
| SAML/OIDC enterprise SSO |
| Stripe payments |
| React Native/Expo |
bash
npm install better-auth按需安装的作用域包:
| 包 | 适用场景 |
|---|---|
| WebAuthn/Passkey认证 |
| SAML/OIDC企业单点登录 |
| Stripe支付集成 |
| React Native/Expo集成 |
Environment Variables
环境变量
env
BETTER_AUTH_SECRET=<32+ chars, generate: openssl rand -base64 32>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<connection string>env
BETTER_AUTH_SECRET=<32位以上字符,生成方式:openssl rand -base64 32>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<数据库连接字符串>Server Config (lib/auth.ts
)
lib/auth.ts服务端配置(lib/auth.ts
)
lib/auth.tsts
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: process.env.DATABASE_URL, // or adapter instance
emailAndPassword: { enabled: true },
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
},
plugins: [], // add plugins here
});
export type Session = typeof auth.$Infer.Session;ts
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: process.env.DATABASE_URL, // 或适配器实例
emailAndPassword: { enabled: true },
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
},
plugins: [], // 在此添加插件
});
export type Session = typeof auth.$Infer.Session;Client Config (lib/auth-client.ts
)
lib/auth-client.ts客户端配置(lib/auth-client.ts
)
lib/auth-client.tsts
import { createAuthClient } from "better-auth/react"; // or /vue, /svelte, /solid, /client
export const authClient = createAuthClient({
plugins: [], // add client plugins here
});ts
import { createAuthClient } from "better-auth/react"; // 或 /vue, /svelte, /solid, /client
export const authClient = createAuthClient({
plugins: [], // 在此添加客户端插件
});Route Handler
路由处理器
| Framework | File | Handler |
|---|---|---|
| Next.js App Router | | |
| Next.js Pages | | |
| Express | any | |
| Hono | route | |
| SvelteKit | | |
| Astro | | |
| Elysia | plugin | |
See references/framework-integrations.md for all frameworks.
| 框架 | 文件 | 处理器 |
|---|---|---|
| Next.js App Router | | |
| Next.js Pages | | |
| Express | 任意文件 | |
| Hono | 路由 | |
| SvelteKit | | |
| Astro | | |
| Elysia | 插件 | |
查看 references/framework-integrations.md 获取所有框架的集成方式。
CLI Commands
CLI命令
bash
npx @better-auth/cli@latest migrate # Apply schema (built-in adapter)
npx @better-auth/cli@latest generate # Generate for Prisma/Drizzle
npx @better-auth/cli@latest generate --output prisma/schema.prisma
npx @better-auth/cli@latest generate --output src/db/auth-schema.tsRe-run after adding/changing plugins.
bash
npx @better-auth/cli@latest migrate # 应用数据库 schema(内置适配器)
npx @better-auth/cli@latest generate # 为Prisma/Drizzle生成代码
npx @better-auth/cli@latest generate --output prisma/schema.prisma
npx @better-auth/cli@latest generate --output src/db/auth-schema.ts添加或修改插件后请重新运行上述命令。
Core Concepts
核心概念
- Server instance (): handles all auth logic, DB, sessions
auth - Client instance (): framework-specific hooks (
authClient,useSession,signIn,signUp)signOut - Plugins: extend both server and client — add endpoints, DB tables, hooks
- Type inference: ,
auth.$Infer.Sessionfor full type safetyauth.$Infer.Session.user - For separate client/server projects:
createAuthClient<typeof auth>()
- 服务端实例():处理所有认证逻辑、数据库操作、会话管理
auth - 客户端实例():框架专属钩子函数(
authClient,useSession,signIn,signUp)signOut - 插件:扩展服务端和客户端功能——添加接口、数据库表、钩子函数
- 类型推导:,
auth.$Infer.Session提供完整的类型安全auth.$Infer.Session.user - 对于分离的客户端/服务端项目:使用
createAuthClient<typeof auth>()
Authentication Methods
认证方式
| Method | Package | Config/Plugin | Reference |
|---|---|---|---|
| Email/Password | built-in | | authentication.md |
| Social OAuth | built-in | | authentication.md |
| Magic Link | built-in | | authentication.md |
| Passkey | | | authentication.md |
| Username | built-in | | authentication.md |
| Email OTP | built-in | | authentication.md |
| Phone Number | built-in | | authentication.md |
| Anonymous | built-in | | authentication.md |
| 方式 | 包 | 配置/插件 | 参考文档 |
|---|---|---|---|
| 邮箱/密码 | 内置 | | authentication.md |
| 社交OAuth | 内置 | | authentication.md |
| 魔法链接 | 内置 | | authentication.md |
| Passkey | | | authentication.md |
| 用户名登录 | 内置 | | authentication.md |
| 邮箱OTP | 内置 | | authentication.md |
| 手机号登录 | 内置 | | authentication.md |
| 匿名登录 | 内置 | | authentication.md |
Plugin Quick Reference
插件速查
Import from dedicated paths for tree-shaking: NOT .
import { twoFactor } from "better-auth/plugins/two-factor"from "better-auth/plugins"| Plugin | Server Import | Client Import | Purpose |
|---|---|---|---|
| | | TOTP, OTP, backup codes |
| | | Multi-tenant orgs, teams, RBAC |
| | | User management, impersonation |
| | | WebAuthn/FIDO2 |
| | | Passwordless email links |
| | | Email one-time passwords |
| | | Username-based auth |
| | | Phone-based auth |
| | | Guest sessions |
| | | API key management |
| | — | Bearer token auth |
| | | JWT tokens |
| | | Multiple active sessions |
| | — | Become OAuth provider |
| | — | Become OIDC provider |
| | | SAML/OIDC enterprise SSO |
| | — | API documentation |
| | — | Extend session data |
| | | Custom OAuth providers |
| | | Google One Tap |
Pattern: server plugin in + client plugin in + re-run CLI migrations.
auth({ plugins: [...] })createAuthClient({ plugins: [...] })See references/plugins.md for detailed usage and custom plugin creation.
为了实现摇树优化,请从专属路径导入插件: 而非 。
import { twoFactor } from "better-auth/plugins/two-factor"from "better-auth/plugins"| 插件 | 服务端导入路径 | 客户端导入路径 | 用途 |
|---|---|---|---|
| | | TOTP、OTP、备份码 |
| | | 多租户组织、团队、RBAC |
| | | 用户管理、身份模拟 |
| | | WebAuthn/FIDO2认证 |
| | | 无密码邮箱链接登录 |
| | | 邮箱一次性密码 |
| | | 用户名认证 |
| | | 手机号认证 |
| | | 访客会话 |
| | | API密钥管理 |
| | — | Bearer令牌认证 |
| | | JWT令牌 |
| | | 多活跃会话 |
| | — | 成为OAuth服务商 |
| | — | 成为OIDC服务商 |
| | | SAML/OIDC企业单点登录 |
| | — | API文档生成 |
| | — | 扩展会话数据 |
| | | 自定义OAuth服务商 |
| | | Google一键登录 |
使用模式:服务端插件配置在 + 客户端插件配置在 + 重新运行CLI迁移命令。
auth({ plugins: [...] })createAuthClient({ plugins: [...] })查看 references/plugins.md 获取详细用法和自定义插件创建指南。
Database Setup
数据库配置
| Adapter | Setup |
|---|---|
| SQLite | Pass |
| PostgreSQL | Pass |
| MySQL | Pass |
| Prisma | |
| Drizzle | |
| MongoDB | |
| Connection string | |
Critical: Config uses ORM model name, NOT DB table name. Prisma model mapping to table → use .
UserusersmodelName: "user"Core schema tables: , , , . Plugins add their own tables.
usersessionaccountverificationSee references/setup.md for full database setup details.
| 适配器 | 配置方式 |
|---|---|
| SQLite | 传入 |
| PostgreSQL | 传入 |
| MySQL | 传入 |
| Prisma | 从 |
| Drizzle | 从 |
| MongoDB | 从 |
| 连接字符串 | |
重要提示:配置中使用의是ORM模型名称,而非数据库表名。例如Prisma模型映射到表,则需设置。
UserusersmodelName: "user"核心schema表:、、、。插件会添加各自的表。
usersessionaccountverification查看 references/setup.md 获取完整的数据库配置详情。
Session Management
会话管理
Key options:
ts
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days (default)
updateAge: 60 * 60 * 24, // refresh every 24h (default)
freshAge: 60 * 60 * 24, // require re-auth after 24h for sensitive ops
cookieCache: {
enabled: true,
maxAge: 300, // 5 min
strategy: "compact", // "compact" | "jwt" | "jwe"
},
}- (Redis/KV): sessions go there by default, not DB
secondaryStorage - Stateless mode: no DB + cookieCache = session in cookie only
- plugin: extend session with custom fields
customSession
See references/sessions.md for full session management details.
关键配置项:
ts
session: {
expiresIn: 60 * 60 * 24 * 7, // 7天(默认值)
updateAge: 60 * 60 * 24, // 每24小时刷新一次(默认值)
freshAge: 60 * 60 * 24, // 敏感操作需在24小时内重新认证(默认值)
cookieCache: {
enabled: true,
maxAge: 300, // 5分钟
strategy: "compact", // "compact" | "jwt" | "jwe"
},
}- (Redis/KV):会话默认存储在此,而非数据库
secondaryStorage - 无状态模式:无数据库 + cookieCache = 会话仅存储在Cookie中
- 插件:扩展会话的自定义字段
customSession
查看 references/sessions.md 获取完整的会话管理详情。
Security Checklist
安全检查清单
| DO | DON'T |
|---|---|
| Use 32+ char secret with high entropy | Commit secrets to version control |
Set | Disable CSRF check ( |
Configure | Disable origin check |
| Enable rate limiting (on by default in prod) | Use |
Configure | Skip email verification setup |
Use | Store OAuth tokens unencrypted if used for API calls |
Set | Return specific error messages ("user not found") |
See references/security.md for complete security hardening guide.
| 建议做法 | 禁止操作 |
|---|---|
| 使用32位以上高熵密钥 | 将密钥提交到版本控制系统 |
生产环境中设置HTTPS的 | 关闭CSRF检查( |
为所有前端配置 | 关闭来源检查 |
| 启用速率限制(生产环境默认开启) | 服务端环境使用 |
无服务器环境中配置 | 跳过邮箱验证设置 |
敏感会话数据使用 | 存储未加密的OAuth令牌(若用于API调用) |
设置 | 返回具体错误信息(如"用户不存在") |
查看 references/security.md 获取完整的安全加固指南。
Common Gotchas
常见陷阱
- Model vs table name — config uses ORM model name, not DB table name
- Plugin schema — re-run CLI after adding/changing plugins
- Secondary storage — sessions go there by default, not DB. Set to persist both
session.storeSessionInDatabase: true - Cookie cache — custom session fields NOT cached, always re-fetched from DB
- Callback URLs — always use absolute URLs with origin (not relative paths)
- Express v5 — use not
"/api/auth/*splat"for catch-all routes"/api/auth/*" - Next.js RSC — add plugin to auth config for server component session access
nextCookies()
- 模型名 vs 表名 — 配置中使用的是ORM模型名称,而非数据库表名
- 插件Schema — 添加或修改插件后需重新运行CLI命令
- 二级存储 — 会话默认存储在此,而非数据库。若需同时存储到数据库,设置
session.storeSessionInDatabase: true - Cookie缓存 — 自定义会话字段不会被缓存,始终从数据库获取
- 回调URL — 始终使用带来源的绝对URL(而非相对路径)
- Express v5 — 通配路由使用而非
"/api/auth/*splat""/api/auth/*" - Next.js RSC — 需在auth配置中添加插件以在服务端组件中访问会话
nextCookies()
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 match exactly |
| Type errors after adding plugin | Re-run CLI generate/migrate |
| Session null in RSC | Add |
| 2FA redirect not working | Add |
| 问题 | 解决方法 |
|---|---|
| "Secret not set" | 添加 |
| "Invalid Origin" | 将域名添加到 |
| Cookie无法设置 | 检查 |
| OAuth回调错误 | 验证服务商控制台中的重定向URI是否完全匹配 |
| 添加插件后出现类型错误 | 重新运行CLI的generate/migrate命令 |
| RSC中会话为null | 添加 |
| 双因素认证重定向不生效 | 在客户端添加 |
Reference Index
参考索引
| File | When to read |
|---|---|
| setup.md | Setting up new project, configuring DB, route handlers |
| authentication.md | Implementing any auth method (email, social, passkey, magic link, etc.) |
| sessions.md | Configuring session expiry, caching, stateless mode, secondary storage |
| security.md | Hardening for production — rate limiting, CSRF, cookies, OAuth security |
| plugins.md | Using or creating plugins, plugin catalog |
| framework-integrations.md | Framework-specific setup (Next.js, Nuxt, SvelteKit, Hono, Express, etc.) |
| two-factor.md | Implementing 2FA (TOTP, OTP, backup codes, trusted devices) |
| organizations.md | Multi-tenant orgs, teams, invitations, RBAC |
| admin.md | User management, roles, banning, impersonation |
| hooks-and-middleware.md | Custom logic via before/after hooks, DB hooks, middleware |
| 文件 | 阅读场景 |
|---|---|
| setup.md | 新项目初始化、数据库配置、路由处理器设置 |
| authentication.md | 实现任意认证方式(邮箱、社交、Passkey、魔法链接等) |
| sessions.md | 配置会话过期、缓存、无状态模式、二级存储 |
| security.md | 生产环境安全加固——速率限制、CSRF、Cookie、OAuth安全 |
| plugins.md | 使用或创建插件、插件目录 |
| framework-integrations.md | 框架专属配置(Next.js、Nuxt、SvelteKit、Hono、Express等) |
| two-factor.md | 实现双因素认证(TOTP、OTP、备份码、可信设备) |
| organizations.md | 多租户组织、团队、邀请、RBAC |
| admin.md | 用户管理、角色、封禁、身份模拟 |
| hooks-and-middleware.md | 通过前后置钩子、数据库钩子、中间件实现自定义逻辑 |