better-auth-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Better 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

环境变量

  • BETTER_AUTH_SECRET
    - Encryption secret (min 32 chars). Generate:
    openssl rand -base64 32
  • BETTER_AUTH_URL
    - Base URL (e.g.,
    https://example.com
    )
Only define
baseURL
/
secret
in config if env vars are NOT set.
  • BETTER_AUTH_SECRET
    - 加密密钥(至少32个字符)。生成方式:
    openssl rand -base64 32
  • BETTER_AUTH_URL
    - 基础URL(例如:
    https://example.com
仅当未设置环境变量时,才在配置中定义
baseURL
/
secret

File Location

文件位置

CLI looks for
auth.ts
in:
./
,
./lib
,
./utils
, or under
./src
. Use
--config
for custom path.
CLI会在
./
./lib
./utils
./src
目录下查找
auth.ts
文件。使用
--config
指定自定义路径。

CLI Commands

CLI命令

  • npx @better-auth/cli@latest migrate
    - Apply schema (built-in adapter)
  • npx @better-auth/cli@latest generate
    - Generate schema for Prisma/Drizzle
  • npx @better-auth/cli mcp --cursor
    - Add MCP to AI tools
Re-run after adding/changing plugins.

  • npx @better-auth/cli@latest migrate
    - 应用数据库Schema(内置适配器)
  • npx @better-auth/cli@latest generate
    - 为Prisma/Drizzle生成Schema
  • npx @better-auth/cli mcp --cursor
    - 为AI工具添加MCP
添加或修改插件后请重新运行。

Core Config Options

核心配置选项

OptionNotes
appName
Optional display name
baseURL
Only if
BETTER_AUTH_URL
not set
basePath
Default
/api/auth
. Set
/
for root.
secret
Only if
BETTER_AUTH_SECRET
not set
database
Required for most features. See adapters docs.
secondaryStorage
Redis/KV for sessions & rate limits
emailAndPassword
{ enabled: true }
to activate
socialProviders
{ google: { clientId, clientSecret }, ... }
plugins
Array of plugins
trustedOrigins
CSRF whitelist

选项说明
appName
可选的显示名称
baseURL
仅当未设置
BETTER_AUTH_URL
时需配置
basePath
默认值
/api/auth
。设置为
/
可将接口置于根路径。
secret
仅当未设置
BETTER_AUTH_SECRET
时需配置
database
大多数功能必填。请查看适配器文档。
secondaryStorage
用于存储会话和速率限制的Redis/KV存储
emailAndPassword
设置
{ enabled: true }
以启用邮箱/密码认证
socialProviders
配置格式示例:
{ google: { clientId, clientSecret }, ... }
plugins
插件数组
trustedOrigins
CSRF白名单

Database

数据库配置

Direct connections: Pass
pg.Pool
,
mysql2
pool,
better-sqlite3
, or
bun:sqlite
instance.
ORM adapters: Import from
better-auth/adapters/drizzle
,
better-auth/adapters/prisma
,
better-auth/adapters/mongodb
.
Critical: Better Auth uses adapter model names, NOT underlying table names. If Prisma model is
User
mapping to table
users
, use
modelName: "user"
(Prisma reference), not
"users"
.

直接连接: 传入
pg.Pool
mysql2
连接池、
better-sqlite3
bun:sqlite
实例。
ORM适配器:
better-auth/adapters/drizzle
better-auth/adapters/prisma
better-auth/adapters/mongodb
导入。
关键提示: Better Auth使用适配器模型名称,而非底层数据库表名。如果Prisma模型是
User
,对应数据库表是
users
,请使用
modelName: "user"
(遵循Prisma命名规则),而非
"users"

Session Management

会话管理

Storage priority:
  1. If
    secondaryStorage
    defined → sessions go there (not DB)
  2. Set
    session.storeSessionInDatabase: true
    to also persist to DB
  3. No database +
    cookieCache
    → fully stateless mode
Cookie cache strategies:
  • compact
    (default) - Base64url + HMAC. Smallest.
  • jwt
    - Standard JWT. Readable but signed.
  • jwe
    - Encrypted. Maximum security.
Key options:
session.expiresIn
(default 7 days),
session.updateAge
(refresh interval),
session.cookieCache.maxAge
,
session.cookieCache.version
(change to invalidate all sessions).

存储优先级:
  1. 若定义了
    secondaryStorage
    → 会话存储在此处(而非数据库)
  2. 设置
    session.storeSessionInDatabase: true
    可同时将会话持久化到数据库
  3. 无数据库 +
    cookieCache
    → 完全无状态模式
Cookie缓存策略:
  • compact
    (默认)- Base64url + HMAC。体积最小。
  • jwt
    - 标准JWT。可读但已签名。
  • jwe
    - 加密。安全性最高。
关键选项:
session.expiresIn
(默认7天)、
session.updateAge
(刷新间隔)、
session.cookieCache.maxAge
session.cookieCache.version
(修改后会使所有会话失效)。

User & Account Config

用户与账户配置

User:
user.modelName
,
user.fields
(column mapping),
user.additionalFields
,
user.changeEmail.enabled
(disabled by default),
user.deleteUser.enabled
(disabled by default).
Account:
account.modelName
,
account.accountLinking.enabled
,
account.storeAccountCookie
(for stateless OAuth).
Required for registration:
email
and
name
fields.

用户配置:
user.modelName
user.fields
(列映射)、
user.additionalFields
user.changeEmail.enabled
(默认禁用)、
user.deleteUser.enabled
(默认禁用)。
账户配置:
account.modelName
account.accountLinking.enabled
account.storeAccountCookie
(用于无状态OAuth)。
注册必填项:
email
name
字段。

Email Flows

邮箱流程

  • emailVerification.sendVerificationEmail
    - Must be defined for verification to work
  • emailVerification.sendOnSignUp
    /
    sendOnSignIn
    - Auto-send triggers
  • emailAndPassword.sendResetPassword
    - Password reset email handler

  • emailVerification.sendVerificationEmail
    - 必须定义此项才能启用邮箱验证功能
  • emailVerification.sendOnSignUp
    /
    sendOnSignIn
    - 自动发送验证邮件的触发条件
  • emailAndPassword.sendResetPassword
    - 密码重置邮箱处理器

Security

安全配置

In
advanced
:
  • useSecureCookies
    - Force HTTPS cookies
  • disableCSRFCheck
    - ⚠️ Security risk
  • disableOriginCheck
    - ⚠️ Security risk
  • crossSubDomainCookies.enabled
    - Share cookies across subdomains
  • ipAddress.ipAddressHeaders
    - Custom IP headers for proxies
  • database.generateId
    - Custom ID generation or
    "serial"
    /
    "uuid"
    /
    false
Rate limiting:
rateLimit.enabled
,
rateLimit.window
,
rateLimit.max
,
rateLimit.storage
("memory" | "database" | "secondary-storage").

advanced
配置中:
  • useSecureCookies
    - 强制使用HTTPS Cookie
  • disableCSRFCheck
    - ⚠️ 存在安全风险
  • disableOriginCheck
    - ⚠️ 存在安全风险
  • crossSubDomainCookies.enabled
    - 在子域名间共享Cookie
  • ipAddress.ipAddressHeaders
    - 代理服务器自定义IP头
  • database.generateId
    - 自定义ID生成方式或
    "serial"
    /
    "uuid"
    /
    false
速率限制:
rateLimit.enabled
rateLimit.window
rateLimit.max
rateLimit.storage
(可选值:"memory" | "database" | "secondary-storage")。

Hooks

钩子函数

Endpoint hooks:
hooks.before
/
hooks.after
- Array of
{ matcher, handler }
. Use
createAuthMiddleware
. Access
ctx.path
,
ctx.context.returned
(after),
ctx.context.session
.
Database hooks:
databaseHooks.user.create.before/after
, same for
session
,
account
. Useful for adding default values or post-creation actions.
Hook context (
ctx.context
):
session
,
secret
,
authCookies
,
password.hash()
/
verify()
,
adapter
,
internalAdapter
,
generateId()
,
tables
,
baseURL
.

端点钩子:
hooks.before
/
hooks.after
-
{ matcher, handler }
数组。使用
createAuthMiddleware
。可访问
ctx.path
ctx.context.returned
(after钩子中)、
ctx.context.session
数据库钩子:
databaseHooks.user.create.before/after
session
account
同理。可用于添加默认值或执行创建后操作。
钩子上下文(
ctx.context
):
session
secret
authCookies
password.hash()
/
verify()
adapter
internalAdapter
generateId()
tables
baseURL

Plugins

插件

Import from dedicated paths for tree-shaking:
import { twoFactor } from "better-auth/plugins/two-factor"
NOT
from "better-auth/plugins"
.
Popular plugins:
twoFactor
,
organization
,
passkey
,
magicLink
,
emailOtp
,
username
,
phoneNumber
,
admin
,
apiKey
,
bearer
,
jwt
,
multiSession
,
sso
,
oauthProvider
,
oidcProvider
,
openAPI
,
genericOAuth
.
Client plugins go in
createAuthClient({ plugins: [...] })
.

从专用路径导入以支持摇树优化:
import { twoFactor } from "better-auth/plugins/two-factor"
而非从
"better-auth/plugins"
导入。
热门插件:
twoFactor
organization
passkey
magicLink
emailOtp
username
phoneNumber
admin
apiKey
bearer
jwt
multiSession
sso
oauthProvider
oidcProvider
openAPI
genericOAuth
客户端插件需在
createAuthClient({ plugins: [...] })
中配置。

Client

客户端

Import from:
better-auth/client
(vanilla),
better-auth/react
,
better-auth/vue
,
better-auth/svelte
,
better-auth/solid
.
Key methods:
signUp.email()
,
signIn.email()
,
signIn.social()
,
signOut()
,
useSession()
,
getSession()
,
revokeSession()
,
revokeSessions()
.

导入路径:
better-auth/client
(原生JavaScript)、
better-auth/react
better-auth/vue
better-auth/svelte
better-auth/solid
核心方法:
signUp.email()
signIn.email()
signIn.social()
signOut()
useSession()
getSession()
revokeSession()
revokeSessions()

Type Safety

类型安全

Infer types:
typeof auth.$Infer.Session
,
typeof auth.$Infer.Session.user
.
For separate client/server projects:
createAuthClient<typeof auth>()
.

推断类型:
typeof auth.$Infer.Session
typeof auth.$Infer.Session.user
对于分离的客户端/服务端项目:
createAuthClient<typeof auth>()

Common Gotchas

常见陷阱

  1. Model vs table name - Config uses ORM model name, not DB table name
  2. Plugin schema - Re-run CLI after adding plugins
  3. Secondary storage - Sessions go there by default, not DB
  4. Cookie cache - Custom session fields NOT cached, always re-fetched
  5. Stateless mode - No DB = session in cookie only, logout on cache expiry
  6. Change email flow - Sends to current email first, then new email

  1. 模型名 vs 表名 - 配置中使用ORM模型名,而非数据库表名
  2. 插件Schema - 添加插件后需重新运行CLI
  3. 二级存储 - 会话默认存储在此处,而非数据库
  4. Cookie缓存 - 自定义会话字段不会被缓存,始终会重新获取
  5. 无状态模式 - 无数据库时,会话仅存储在Cookie中,缓存过期后自动登出
  6. 邮箱修改流程 - 先发送验证邮件到当前邮箱,再发送到新邮箱

Resources

资源