better-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Better 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-auth
Scoped packages (as needed):
PackageUse case
@better-auth/passkey
WebAuthn/Passkey auth
@better-auth/sso
SAML/OIDC enterprise SSO
@better-auth/stripe
Stripe payments
@better-auth/expo
React Native/Expo
bash
npm install better-auth
按需安装的作用域包:
适用场景
@better-auth/passkey
WebAuthn/Passkey认证
@better-auth/sso
SAML/OIDC企业单点登录
@better-auth/stripe
Stripe支付集成
@better-auth/expo
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

ts
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

ts
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

路由处理器

FrameworkFileHandler
Next.js App Router
app/api/auth/[...all]/route.ts
toNextJsHandler(auth)
→ export
{ GET, POST }
Next.js Pages
pages/api/auth/[...all].ts
toNextJsHandler(auth)
→ default export
Expressany
app.all("/api/auth/*splat", toNodeHandler(auth))
Honoroute
app.on(["POST","GET"], "/api/auth/**", (c) => auth.handler(c.req.raw))
SvelteKit
hooks.server.ts
svelteKitHandler({ auth, event })
Astro
pages/api/auth/[...all].ts
toAstroHandler(auth)
Elysiaplugin
new Elysia().mount(auth.handler)
See references/framework-integrations.md for all frameworks.
框架文件处理器
Next.js App Router
app/api/auth/[...all]/route.ts
toNextJsHandler(auth)
→ 导出
{ GET, POST }
Next.js Pages
pages/api/auth/[...all].ts
toNextJsHandler(auth)
→ 默认导出
Express任意文件
app.all("/api/auth/*splat", toNodeHandler(auth))
Hono路由
app.on(["POST","GET"], "/api/auth/**", (c) => auth.handler(c.req.raw))
SvelteKit
hooks.server.ts
svelteKitHandler({ auth, event })
Astro
pages/api/auth/[...all].ts
toAstroHandler(auth)
Elysia插件
new Elysia().mount(auth.handler)
查看 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.ts
Re-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 (
    auth
    ): handles all auth logic, DB, sessions
  • Client instance (
    authClient
    ): framework-specific hooks (
    useSession
    ,
    signIn
    ,
    signUp
    ,
    signOut
    )
  • Plugins: extend both server and client — add endpoints, DB tables, hooks
  • Type inference:
    auth.$Infer.Session
    ,
    auth.$Infer.Session.user
    for full type safety
  • 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

认证方式

MethodPackageConfig/PluginReference
Email/Passwordbuilt-in
emailAndPassword: { enabled: true }
authentication.md
Social OAuthbuilt-in
socialProviders: { google: {...} }
authentication.md
Magic Linkbuilt-in
magicLink()
plugin
authentication.md
Passkey
@better-auth/passkey
passkey()
plugin
authentication.md
Usernamebuilt-in
username()
plugin
authentication.md
Email OTPbuilt-in
emailOtp()
plugin
authentication.md
Phone Numberbuilt-in
phoneNumber()
plugin
authentication.md
Anonymousbuilt-in
anonymous()
plugin
authentication.md
方式配置/插件参考文档
邮箱/密码内置
emailAndPassword: { enabled: true }
authentication.md
社交OAuth内置
socialProviders: { google: {...} }
authentication.md
魔法链接内置
magicLink()
插件
authentication.md
Passkey
@better-auth/passkey
passkey()
插件
authentication.md
用户名登录内置
username()
插件
authentication.md
邮箱OTP内置
emailOtp()
插件
authentication.md
手机号登录内置
phoneNumber()
插件
authentication.md
匿名登录内置
anonymous()
插件
authentication.md

Plugin Quick Reference

插件速查

Import from dedicated paths for tree-shaking:
import { twoFactor } from "better-auth/plugins/two-factor"
NOT
from "better-auth/plugins"
.
PluginServer ImportClient ImportPurpose
twoFactor
better-auth/plugins/two-factor
twoFactorClient
TOTP, OTP, backup codes
organization
better-auth/plugins/organization
organizationClient
Multi-tenant orgs, teams, RBAC
admin
better-auth/plugins/admin
adminClient
User management, impersonation
passkey
@better-auth/passkey
passkeyClient
WebAuthn/FIDO2
magicLink
better-auth/plugins/magic-link
magicLinkClient
Passwordless email links
emailOtp
better-auth/plugins/email-otp
emailOtpClient
Email one-time passwords
username
better-auth/plugins/username
usernameClient
Username-based auth
phoneNumber
better-auth/plugins/phone-number
phoneNumberClient
Phone-based auth
anonymous
better-auth/plugins/anonymous
anonymousClient
Guest sessions
apiKey
better-auth/plugins/api-key
apiKeyClient
API key management
bearer
better-auth/plugins/bearer
Bearer token auth
jwt
better-auth/plugins/jwt
jwtClient
JWT tokens
multiSession
better-auth/plugins/multi-session
multiSessionClient
Multiple active sessions
oauthProvider
better-auth/plugins/oauth-provider
Become OAuth provider
oidcProvider
better-auth/plugins/oidc-provider
Become OIDC provider
sso
@better-auth/sso
ssoClient
SAML/OIDC enterprise SSO
openAPI
better-auth/plugins/open-api
API documentation
customSession
better-auth/plugins/custom-session
Extend session data
genericOAuth
better-auth/plugins/generic-oauth
genericOAuthClient
Custom OAuth providers
oneTap
better-auth/plugins/one-tap
oneTapClient
Google One Tap
Pattern: server plugin in
auth({ plugins: [...] })
+ client plugin in
createAuthClient({ plugins: [...] })
+ re-run CLI migrations.
See references/plugins.md for detailed usage and custom plugin creation.
为了实现摇树优化,请从专属路径导入插件:
import { twoFactor } from "better-auth/plugins/two-factor"
而非
from "better-auth/plugins"
插件服务端导入路径客户端导入路径用途
twoFactor
better-auth/plugins/two-factor
twoFactorClient
TOTP、OTP、备份码
organization
better-auth/plugins/organization
organizationClient
多租户组织、团队、RBAC
admin
better-auth/plugins/admin
adminClient
用户管理、身份模拟
passkey
@better-auth/passkey
passkeyClient
WebAuthn/FIDO2认证
magicLink
better-auth/plugins/magic-link
magicLinkClient
无密码邮箱链接登录
emailOtp
better-auth/plugins/email-otp
emailOtpClient
邮箱一次性密码
username
better-auth/plugins/username
usernameClient
用户名认证
phoneNumber
better-auth/plugins/phone-number
phoneNumberClient
手机号认证
anonymous
better-auth/plugins/anonymous
anonymousClient
访客会话
apiKey
better-auth/plugins/api-key
apiKeyClient
API密钥管理
bearer
better-auth/plugins/bearer
Bearer令牌认证
jwt
better-auth/plugins/jwt
jwtClient
JWT令牌
multiSession
better-auth/plugins/multi-session
multiSessionClient
多活跃会话
oauthProvider
better-auth/plugins/oauth-provider
成为OAuth服务商
oidcProvider
better-auth/plugins/oidc-provider
成为OIDC服务商
sso
@better-auth/sso
ssoClient
SAML/OIDC企业单点登录
openAPI
better-auth/plugins/open-api
API文档生成
customSession
better-auth/plugins/custom-session
扩展会话数据
genericOAuth
better-auth/plugins/generic-oauth
genericOAuthClient
自定义OAuth服务商
oneTap
better-auth/plugins/one-tap
oneTapClient
Google一键登录
使用模式:服务端插件配置在
auth({ plugins: [...] })
+ 客户端插件配置在
createAuthClient({ plugins: [...] })
+ 重新运行CLI迁移命令。
查看 references/plugins.md 获取详细用法和自定义插件创建指南。

Database Setup

数据库配置

AdapterSetup
SQLitePass
better-sqlite3
or
bun:sqlite
instance
PostgreSQLPass
pg.Pool
instance
MySQLPass
mysql2
pool
Prisma
prismaAdapter(prisma, { provider: "postgresql" })
from
better-auth/adapters/prisma
Drizzle
drizzleAdapter(db, { provider: "pg" })
from
better-auth/adapters/drizzle
MongoDB
mongodbAdapter(db)
from
better-auth/adapters/mongodb
Connection string
database: process.env.DATABASE_URL
(uses built-in Kysely)
Critical: Config uses ORM model name, NOT DB table name. Prisma model
User
mapping to table
users
→ use
modelName: "user"
.
Core schema tables:
user
,
session
,
account
,
verification
. Plugins add their own tables.
See references/setup.md for full database setup details.
适配器配置方式
SQLite传入
better-sqlite3
bun:sqlite
实例
PostgreSQL传入
pg.Pool
实例
MySQL传入
mysql2
连接池
Prisma
better-auth/adapters/prisma
导入
prismaAdapter(prisma, { provider: "postgresql" })
Drizzle
better-auth/adapters/drizzle
导入
drizzleAdapter(db, { provider: "pg" })
MongoDB
better-auth/adapters/mongodb
导入
mongodbAdapter(db)
连接字符串
database: process.env.DATABASE_URL
(使用内置Kysely)
重要提示:配置中使用의是ORM模型名称,而非数据库表名。例如Prisma模型
User
映射到表
users
,则需设置
modelName: "user"
核心schema表:
user
session
account
verification
。插件会添加各自的表。
查看 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"
  },
}
  • secondaryStorage
    (Redis/KV): sessions go there by default, not DB
  • Stateless mode: no DB + cookieCache = session in cookie only
  • customSession
    plugin
    : extend session with custom fields
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"
  },
}
  • secondaryStorage
    (Redis/KV):会话默认存储在此,而非数据库
  • 无状态模式:无数据库 + cookieCache = 会话仅存储在Cookie中
  • customSession
    插件
    :扩展会话的自定义字段
查看 references/sessions.md 获取完整的会话管理详情。

Security Checklist

安全检查清单

DODON'T
Use 32+ char secret with high entropyCommit secrets to version control
Set
baseURL
with HTTPS in production
Disable CSRF check (
disableCSRFCheck
)
Configure
trustedOrigins
for all frontends
Disable origin check
Enable rate limiting (on by default in prod)Use
"memory"
rate limit storage in serverless
Configure
backgroundTasks.handler
on serverless
Skip email verification setup
Use
"jwe"
cookie cache for sensitive session data
Store OAuth tokens unencrypted if used for API calls
Set
revokeSessionsOnPasswordReset: true
Return specific error messages ("user not found")
See references/security.md for complete security hardening guide.
建议做法禁止操作
使用32位以上高熵密钥将密钥提交到版本控制系统
生产环境中设置HTTPS的
baseURL
关闭CSRF检查(
disableCSRFCheck
为所有前端配置
trustedOrigins
关闭来源检查
启用速率限制(生产环境默认开启)服务端环境使用
"memory"
类型的速率限制存储
无服务器环境中配置
backgroundTasks.handler
跳过邮箱验证设置
敏感会话数据使用
"jwe"
类型的cookie缓存
存储未加密的OAuth令牌(若用于API调用)
设置
revokeSessionsOnPasswordReset: true
返回具体错误信息(如"用户不存在")
查看 references/security.md 获取完整的安全加固指南。

Common Gotchas

常见陷阱

  1. Model vs table name — config uses ORM model name, not DB table name
  2. Plugin schema — re-run CLI after adding/changing plugins
  3. Secondary storage — sessions go there by default, not DB. Set
    session.storeSessionInDatabase: true
    to persist both
  4. Cookie cache — custom session fields NOT cached, always re-fetched from DB
  5. Callback URLs — always use absolute URLs with origin (not relative paths)
  6. Express v5 — use
    "/api/auth/*splat"
    not
    "/api/auth/*"
    for catch-all routes
  7. Next.js RSC — add
    nextCookies()
    plugin to auth config for server component session access
  1. 模型名 vs 表名 — 配置中使用的是ORM模型名称,而非数据库表名
  2. 插件Schema — 添加或修改插件后需重新运行CLI命令
  3. 二级存储 — 会话默认存储在此,而非数据库。若需同时存储到数据库,设置
    session.storeSessionInDatabase: true
  4. Cookie缓存 — 自定义会话字段不会被缓存,始终从数据库获取
  5. 回调URL — 始终使用带来源的绝对URL(而非相对路径)
  6. Express v5 — 通配路由使用
    "/api/auth/*splat"
    而非
    "/api/auth/*"
  7. Next.js RSC — 需在auth配置中添加
    nextCookies()
    插件以在服务端组件中访问会话

Troubleshooting

问题排查

IssueFix
"Secret not set"Add
BETTER_AUTH_SECRET
env var
"Invalid Origin"Add domain to
trustedOrigins
Cookies not settingCheck
baseURL
matches domain; enable secure cookies in prod
OAuth callback errorsVerify redirect URIs in provider dashboard match exactly
Type errors after adding pluginRe-run CLI generate/migrate
Session null in RSCAdd
nextCookies()
plugin
2FA redirect not workingAdd
twoFactorClient
with
onTwoFactorRedirect
to client
问题解决方法
"Secret not set"添加
BETTER_AUTH_SECRET
环境变量
"Invalid Origin"将域名添加到
trustedOrigins
Cookie无法设置检查
baseURL
是否与域名匹配;生产环境启用安全Cookie
OAuth回调错误验证服务商控制台中的重定向URI是否完全匹配
添加插件后出现类型错误重新运行CLI的generate/migrate命令
RSC中会话为null添加
nextCookies()
插件
双因素认证重定向不生效在客户端添加
twoFactorClient
并配置
onTwoFactorRedirect

Reference Index

参考索引

FileWhen to read
setup.mdSetting up new project, configuring DB, route handlers
authentication.mdImplementing any auth method (email, social, passkey, magic link, etc.)
sessions.mdConfiguring session expiry, caching, stateless mode, secondary storage
security.mdHardening for production — rate limiting, CSRF, cookies, OAuth security
plugins.mdUsing or creating plugins, plugin catalog
framework-integrations.mdFramework-specific setup (Next.js, Nuxt, SvelteKit, Hono, Express, etc.)
two-factor.mdImplementing 2FA (TOTP, OTP, backup codes, trusted devices)
organizations.mdMulti-tenant orgs, teams, invitations, RBAC
admin.mdUser management, roles, banning, impersonation
hooks-and-middleware.mdCustom 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通过前后置钩子、数据库钩子、中间件实现自定义逻辑