better-auth-best-practices by aifuxi/fuxiaochen
npx skills add https://github.com/aifuxi/fuxiaochen --skill better-auth-best-practices请始终查阅 better-auth.com/docs 以获取代码示例和最新的 API 信息。
Better Auth 是一个 TypeScript 优先、框架无关的身份验证框架,通过插件支持电子邮件/密码、OAuth、魔法链接、通行密钥等功能。
BETTER_AUTH_SECRET - 加密密钥(至少 32 个字符)。生成命令:openssl rand -base64 32BETTER_AUTH_URL - 基础 URL(例如,https://example.com)如果未设置环境变量,才需要在配置中定义 baseURL/secret。
CLI 在以下位置查找 auth.ts 文件:、、 或 目录下。使用 参数指定自定义路径。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
././lib./utils./src--confignpx @better-auth/cli@latest migrate - 应用数据库模式(内置适配器)npx @better-auth/cli@latest generate - 为 Prisma/Drizzle 生成数据库模式npx @better-auth/cli mcp --cursor - 将 MCP 添加到 AI 工具添加或更改插件后,请重新运行相关命令。
| 选项 | 说明 |
|---|---|
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 白名单 |
直接连接: 传递 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"。
存储优先级:
secondaryStorage → 会话存储在那里(而非数据库)session.storeSessionInDatabase: true 以同时持久化到数据库cookieCache → 完全无状态模式Cookie 缓存策略:
compact(默认)- Base64url + HMAC。体积最小。jwt - 标准 JWT。可读但已签名。jwe - 加密的。安全性最高。关键选项: session.expiresIn(默认 7 天)、session.updateAge(刷新间隔)、session.cookieCache.maxAge、session.cookieCache.version(更改此值将使所有会话失效)。
用户: user.modelName、user.fields(列映射)、user.additionalFields、user.changeEmail.enabled(默认禁用)、user.deleteUser.enabled(默认禁用)。
账户: account.modelName、account.accountLinking.enabled、account.storeAccountCookie(用于无状态 OAuth)。
注册必需字段: email 和 name 字段。
emailVerification.sendVerificationEmail - 必须定义此函数,验证功能才能工作emailVerification.sendOnSignUp / sendOnSignIn - 自动发送邮件的触发器emailAndPassword.sendResetPassword - 密码重置邮件处理器在 advanced 配置中:
useSecureCookies - 强制使用 HTTPS CookiedisableCSRFCheck - ⚠️ 安全风险disableOriginCheck - ⚠️ 安全风险crossSubDomainCookies.enabled - 跨子域共享 CookieipAddress.ipAddressHeaders - 用于代理的自定义 IP 头database.generateId - 自定义 ID 生成方式或 "serial"/"uuid"/false速率限制: rateLimit.enabled、rateLimit.window、rateLimit.max、rateLimit.storage("memory" | "database" | "secondary-storage")。
端点钩子: 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。
从专用路径导入以实现 Tree-shaking:
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: [...] }) 中。
从以下位置导入:better-auth/client(原生)、better-auth/react、better-auth/vue、better-auth/svelte、better-auth/solid。
关键方法:signUp.email()、signIn.email()、signIn.social()、signOut()、useSession()、getSession()、revokeSession()、revokeSessions()。
推断类型:typeof auth.$Infer.Session、typeof auth.$Infer.Session.user。
对于独立的客户端/服务器项目:createAuthClient<typeof auth>()。
每周安装量
1
代码仓库
GitHub 星标数
440
首次出现
1 天前
安全审计
安装于
zencoder1
amp1
cline1
openclaw1
opencode1
cursor1
Always consultbetter-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_SECRET - Encryption secret (min 32 chars). Generate: openssl rand -base64 32BETTER_AUTH_URL - Base URL (e.g., https://example.com)Only define baseURL/secret in config if env vars are NOT set.
CLI looks for auth.ts in: ./, ./lib, ./utils, or under ./src. Use --config for custom path.
npx @better-auth/cli@latest migrate - Apply schema (built-in adapter)npx @better-auth/cli@latest generate - Generate schema for Prisma/Drizzlenpx @better-auth/cli mcp --cursor - Add MCP to AI toolsRe-run after adding/changing plugins.
| Option | Notes |
|---|---|
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 |
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".
Storage priority:
secondaryStorage defined → sessions go there (not DB)session.storeSessionInDatabase: true to also persist to DBcookieCache → fully stateless modeCookie 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).
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.
emailVerification.sendVerificationEmail - Must be defined for verification to workemailVerification.sendOnSignUp / sendOnSignIn - Auto-send triggersemailAndPassword.sendResetPassword - Password reset email handlerInadvanced:
useSecureCookies - Force HTTPS cookiesdisableCSRFCheck - ⚠️ Security riskdisableOriginCheck - ⚠️ Security riskcrossSubDomainCookies.enabled - Share cookies across subdomainsipAddress.ipAddressHeaders - Custom IP headers for proxiesdatabase.generateId - Custom ID generation or "serial"/"uuid"/falseRate limiting: rateLimit.enabled, rateLimit.window, rateLimit.max, rateLimit.storage ("memory" | "database" | "secondary-storage").
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.
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, , , , , .
Client plugins go in createAuthClient({ plugins: [...] }).
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().
Infer types: typeof auth.$Infer.Session, typeof auth.$Infer.Session.user.
For separate client/server projects: createAuthClient<typeof auth>().
Weekly Installs
1
Repository
GitHub Stars
440
First Seen
1 day ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
zencoder1
amp1
cline1
openclaw1
opencode1
cursor1
Better Auth 最佳实践指南:集成、配置与安全设置完整教程
30,700 周安装
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 |
ssooauthProvideroidcProvideropenAPIgenericOAuth