better-auth-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBetter Auth Integration Guide
Better Auth 集成指南
Always consult better-auth.com/docs for code examples and latest API.
Better Auth is a TypeScript-first, framework-agnostic auth framework supporting email/password, OAuth, magic links, passkeys, and more via plugins.
始终参考better-auth.com/docs获取代码示例和最新API。
Better Auth是一款优先支持TypeScript、与框架无关的身份验证框架,通过插件支持邮箱/密码、OAuth、魔法链接、通行密钥等多种认证方式。
Quick Reference
快速参考
Environment Variables
环境变量
- - Encryption secret (min 32 chars). Generate:
BETTER_AUTH_SECRETopenssl rand -base64 32 - - Base URL (e.g.,
BETTER_AUTH_URL)https://example.com
Only define / in config if env vars are NOT set.
baseURLsecret- - 加密密钥(至少32个字符)。生成方式:
BETTER_AUTH_SECRETopenssl rand -base64 32 - - 基础URL(例如:
BETTER_AUTH_URL)https://example.com
仅当未设置环境变量时,才在配置中定义/。
baseURLsecretFile Location
文件位置
CLI looks for in: , , , or under . Use for custom path.
auth.ts././lib./utils./src--configCLI会在、、或目录下查找文件。使用指定自定义路径。
././lib./utils./srcauth.ts--configCLI Commands
CLI命令
- - Apply schema (built-in adapter)
npx @better-auth/cli@latest migrate - - Generate schema for Prisma/Drizzle
npx @better-auth/cli@latest generate - - Add MCP to AI tools
npx @better-auth/cli mcp --cursor
Re-run after adding/changing plugins.
- - 应用数据库Schema(内置适配器)
npx @better-auth/cli@latest migrate - - 为Prisma/Drizzle生成Schema
npx @better-auth/cli@latest generate - - 为AI工具添加MCP
npx @better-auth/cli mcp --cursor
添加或修改插件后请重新运行。
Core Config Options
核心配置选项
| Option | Notes |
|---|---|
| Optional display name |
| Only if |
| Default |
| Only if |
| Required for most features. See adapters docs. |
| Redis/KV for sessions & rate limits |
| |
| |
| Array of plugins |
| CSRF whitelist |
| 选项 | 说明 |
|---|---|
| 可选的显示名称 |
| 仅当未设置 |
| 默认值 |
| 仅当未设置 |
| 大多数功能必填。请查看适配器文档。 |
| 用于存储会话和速率限制的Redis/KV存储 |
| 设置 |
| 配置格式示例: |
| 插件数组 |
| CSRF白名单 |
Database
数据库配置
Direct connections: Pass , pool, , or instance.
pg.Poolmysql2better-sqlite3bun:sqliteORM adapters: Import from , , .
better-auth/adapters/drizzlebetter-auth/adapters/prismabetter-auth/adapters/mongodbCritical: Better Auth uses adapter model names, NOT underlying table names. If Prisma model is mapping to table , use (Prisma reference), not .
UserusersmodelName: "user""users"直接连接: 传入、连接池、或实例。
pg.Poolmysql2better-sqlite3bun:sqliteORM适配器: 从、、导入。
better-auth/adapters/drizzlebetter-auth/adapters/prismabetter-auth/adapters/mongodb关键提示: Better Auth使用适配器模型名称,而非底层数据库表名。如果Prisma模型是,对应数据库表是,请使用(遵循Prisma命名规则),而非。
UserusersmodelName: "user""users"Session Management
会话管理
Storage priority:
- If defined → sessions go there (not DB)
secondaryStorage - Set to also persist to DB
session.storeSessionInDatabase: true - No database + → fully stateless mode
cookieCache
Cookie cache strategies:
- (default) - Base64url + HMAC. Smallest.
compact - - Standard JWT. Readable but signed.
jwt - - Encrypted. Maximum security.
jwe
Key options: (default 7 days), (refresh interval), , (change to invalidate all sessions).
session.expiresInsession.updateAgesession.cookieCache.maxAgesession.cookieCache.version存储优先级:
- 若定义了→ 会话存储在此处(而非数据库)
secondaryStorage - 设置可同时将会话持久化到数据库
session.storeSessionInDatabase: true - 无数据库 + → 完全无状态模式
cookieCache
Cookie缓存策略:
- (默认)- Base64url + HMAC。体积最小。
compact - - 标准JWT。可读但已签名。
jwt - - 加密。安全性最高。
jwe
关键选项: (默认7天)、(刷新间隔)、、(修改后会使所有会话失效)。
session.expiresInsession.updateAgesession.cookieCache.maxAgesession.cookieCache.versionUser & Account Config
用户与账户配置
User: , (column mapping), , (disabled by default), (disabled by default).
user.modelNameuser.fieldsuser.additionalFieldsuser.changeEmail.enableduser.deleteUser.enabledAccount: , , (for stateless OAuth).
account.modelNameaccount.accountLinking.enabledaccount.storeAccountCookieRequired for registration: and fields.
emailname用户配置: 、(列映射)、、(默认禁用)、(默认禁用)。
user.modelNameuser.fieldsuser.additionalFieldsuser.changeEmail.enableduser.deleteUser.enabled账户配置: 、、(用于无状态OAuth)。
account.modelNameaccount.accountLinking.enabledaccount.storeAccountCookie注册必填项: 和字段。
emailnameEmail Flows
邮箱流程
- - Must be defined for verification to work
emailVerification.sendVerificationEmail - /
emailVerification.sendOnSignUp- Auto-send triggerssendOnSignIn - - Password reset email handler
emailAndPassword.sendResetPassword
- - 必须定义此项才能启用邮箱验证功能
emailVerification.sendVerificationEmail - /
emailVerification.sendOnSignUp- 自动发送验证邮件的触发条件sendOnSignIn - - 密码重置邮箱处理器
emailAndPassword.sendResetPassword
Security
安全配置
In :
advanced- - Force HTTPS cookies
useSecureCookies - - ⚠️ Security risk
disableCSRFCheck - - ⚠️ Security risk
disableOriginCheck - - Share cookies across subdomains
crossSubDomainCookies.enabled - - Custom IP headers for proxies
ipAddress.ipAddressHeaders - - Custom ID generation or
database.generateId/"serial"/"uuid"false
Rate limiting: , , , ("memory" | "database" | "secondary-storage").
rateLimit.enabledrateLimit.windowrateLimit.maxrateLimit.storage在配置中:
advanced- - 强制使用HTTPS Cookie
useSecureCookies - - ⚠️ 存在安全风险
disableCSRFCheck - - ⚠️ 存在安全风险
disableOriginCheck - - 在子域名间共享Cookie
crossSubDomainCookies.enabled - - 代理服务器自定义IP头
ipAddress.ipAddressHeaders - - 自定义ID生成方式或
database.generateId/"serial"/"uuid"false
速率限制: 、、、(可选值:"memory" | "database" | "secondary-storage")。
rateLimit.enabledrateLimit.windowrateLimit.maxrateLimit.storageHooks
钩子函数
Endpoint hooks: / - Array of . Use . Access , (after), .
hooks.beforehooks.after{ matcher, handler }createAuthMiddlewarectx.pathctx.context.returnedctx.context.sessionDatabase hooks: , same for , . Useful for adding default values or post-creation actions.
databaseHooks.user.create.before/aftersessionaccountHook context (): , , , /, , , , , .
ctx.contextsessionsecretauthCookiespassword.hash()verify()adapterinternalAdaptergenerateId()tablesbaseURL端点钩子: / - 数组。使用。可访问、(after钩子中)、。
hooks.beforehooks.after{ matcher, handler }createAuthMiddlewarectx.pathctx.context.returnedctx.context.session数据库钩子: ,和同理。可用于添加默认值或执行创建后操作。
databaseHooks.user.create.before/aftersessionaccount钩子上下文(): 、、、/、、、、、。
ctx.contextsessionsecretauthCookiespassword.hash()verify()adapterinternalAdaptergenerateId()tablesbaseURLPlugins
插件
Import from dedicated paths for tree-shaking:
import { twoFactor } from "better-auth/plugins/two-factor"NOT .
from "better-auth/plugins"Popular plugins: , , , , , , , , , , , , , , , , .
twoFactororganizationpasskeymagicLinkemailOtpusernamephoneNumberadminapiKeybearerjwtmultiSessionssooauthProvideroidcProvideropenAPIgenericOAuthClient plugins go in .
createAuthClient({ plugins: [...] })从专用路径导入以支持摇树优化:
import { twoFactor } from "better-auth/plugins/two-factor"而非从导入。
"better-auth/plugins"热门插件: 、、、、、、、、、、、、、、、、。
twoFactororganizationpasskeymagicLinkemailOtpusernamephoneNumberadminapiKeybearerjwtmultiSessionssooauthProvideroidcProvideropenAPIgenericOAuth客户端插件需在中配置。
createAuthClient({ plugins: [...] })Client
客户端
Import from: (vanilla), , , , .
better-auth/clientbetter-auth/reactbetter-auth/vuebetter-auth/sveltebetter-auth/solidKey methods: , , , , , , , .
signUp.email()signIn.email()signIn.social()signOut()useSession()getSession()revokeSession()revokeSessions()导入路径:(原生JavaScript)、、、、。
better-auth/clientbetter-auth/reactbetter-auth/vuebetter-auth/sveltebetter-auth/solid核心方法:、、、、、、、。
signUp.email()signIn.email()signIn.social()signOut()useSession()getSession()revokeSession()revokeSessions()Type Safety
类型安全
Infer types: , .
typeof auth.$Infer.Sessiontypeof auth.$Infer.Session.userFor separate client/server projects: .
createAuthClient<typeof auth>()推断类型:、。
typeof auth.$Infer.Sessiontypeof auth.$Infer.Session.user对于分离的客户端/服务端项目:。
createAuthClient<typeof auth>()Common Gotchas
常见陷阱
- Model vs table name - Config uses ORM model name, not DB table name
- Plugin schema - Re-run CLI after adding plugins
- Secondary storage - Sessions go there by default, not DB
- Cookie cache - Custom session fields NOT cached, always re-fetched
- Stateless mode - No DB = session in cookie only, logout on cache expiry
- Change email flow - Sends to current email first, then new email
- 模型名 vs 表名 - 配置中使用ORM模型名,而非数据库表名
- 插件Schema - 添加插件后需重新运行CLI
- 二级存储 - 会话默认存储在此处,而非数据库
- Cookie缓存 - 自定义会话字段不会被缓存,始终会重新获取
- 无状态模式 - 无数据库时,会话仅存储在Cookie中,缓存过期后自动登出
- 邮箱修改流程 - 先发送验证邮件到当前邮箱,再发送到新邮箱