better-auth-best-practices by better-auth/skills
npx skills add https://github.com/better-auth/skills --skill better-auth-best-practices请始终查阅 better-auth.com/docs 以获取代码示例和最新 API。
npm install better-authBETTER_AUTH_SECRET 和 BETTER_AUTH_URLauth.tsnpx @better-auth/cli@latest migrateGET /api/auth/ok — 应返回 { status: "ok" }广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
BETTER_AUTH_SECRET - 加密密钥(至少 32 个字符)。生成方式:openssl rand -base64 32BETTER_AUTH_URL - 基础 URL(例如,https://example.com)如果环境变量未设置,才需要在配置中定义 baseURL/secret。
CLI 在以下位置查找 auth.ts:./、./lib、./utils 或 ./src 目录下。使用 --config 指定自定义路径。
npx @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"
不要使用 from "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>()。
每周安装量
20.7K
代码仓库
GitHub 星标
150
首次出现
2026年1月19日
安全审计
安装于
opencode14.2K
codex13.3K
gemini-cli13.1K
github-copilot12.9K
claude-code12.4K
cursor11.9K
Always consultbetter-auth.com/docs for code examples and latest API.
npm install better-authBETTER_AUTH_SECRET and BETTER_AUTH_URLauth.ts with database + confignpx @better-auth/cli@latest migrateGET /api/auth/ok — should return { status: "ok" }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
20.7K
Repository
GitHub Stars
150
First Seen
Jan 19, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode14.2K
codex13.3K
gemini-cli13.1K
github-copilot12.9K
claude-code12.4K
cursor11.9K
97,400 周安装
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