☰
Better Auth 集成实战指南:从零配置 TypeScript 全栈认证
2026/10/9 2:15:11 网站建设 项目流程

【免费下载链接】autoskills

One command. Your entire AI skill stack. Installed.

项目地址:https://gitcode.com/gh_mirrors/au/autoskills
点击查看免费下载

导读

本文以 autoskills 技能仓库中的 best-practices/SKILL.md 为核心骨架,系统讲解 Better Auth 的完整接入流程:从安装、环境变量、数据库适配器、会话管理、用户与账户模型、邮箱流程、安全加固、钩子(Hooks)、插件体系到客户端接入与类型安全,并结合 skills-map.ts 中 Better Auth 的自动检测与技能挂载逻辑,说明该技能在 autoskills 项目中的实际定位。读完本文,你将能够独立完成一个具备邮箱/密码登录、OAuth、2FA、组织与 RBAC 的 TypeScript 认证系统,并避开模型名/表名混用、插件 schema 未同步等高频坑。

背景:Better Auth 在 autoskills 技能体系中的定位

autoskills 是一个"一条命令安装整套 AI 技能栈"的工具:它扫描项目的package.json、锁文件与配置文件,自动识别技术栈并安装对应的 Agent 技能。在 skills-map.ts 中,better-auth通过packages: ["better-auth"]被识别,并挂载四个技能:

  • better-auth/skills/best-practices(本文主体)
  • better-auth/skills/emailAndPassword
  • better-auth/skills/organization
  • better-auth/skills/twoFactor

这些技能文件最终被安装到.claude/skills等目录下,供 AI 编码助手在开发认证功能时自动查阅。而仓库中的 validate-registry.mjs 会逐文件校验技能清单的 SHA-256 哈希与 bundleHash,确保安装到用户项目的技能内容与注册表完全一致。这意味着:本文所述配置方式,就是 Better Auth 官方技能所推荐的标准做法。

标准接入工作流

按以下六步即可完成 Better Auth 的最小可用接入:

  1. 安装依赖:npm install better-auth
  2. 设置环境变量BETTER_AUTH_SECRET与BETTER_AUTH_URL
  3. 创建auth.ts,配置数据库与核心选项
  4. 为你的框架创建路由处理器(route handler)
  5. 执行npx @better-auth/cli@latest migrate同步数据库 schema
  6. 验证:调用GET /api/auth/ok,应返回{ status: "ok" }

其中第 3、4 步因框架而异——Next.js 使用 Route Handler,Hono/Express 使用中间件,Astro 使用 Server Endpoint。CLI 会自动在以下位置寻找auth.ts:./、./lib、./utils、./src;如果你的文件放在其他位置,用--config指定自定义路径。

环境变量

变量说明
BETTER_AUTH_SECRET加密密钥,最少 32 个字符。生成命令:openssl rand -base64 32
BETTER_AUTH_URL基础 URL,例如https://example.com

只有在环境变量未设置时,才需要在配置中显式定义baseURL与secret。这一约定避免了密钥硬编码进源码,也便于在不同环境(开发/预发/生产)间切换。

CLI 常用命令

命令作用
npx @better-auth/cli@latest migrate为内置数据库适配器应用 schema
npx @better-auth/cli@latest generate为 Prisma / Drizzle 生成 schema 文件
npx @better-auth/cli mcp --cursor将 Better Auth 作为 MCP 接入 AI 工具

重要:每当你新增或修改插件后,都必须重新运行上述 CLI 命令,否则新增表/字段不会同步到数据库。

核心配置选项

betterAuth()接受一个配置对象,常用选项如下:

选项说明
appName可选,用于显示的应用名
baseURL仅在未设置BETTER_AUTH_URL时使用
basePath默认/api/auth;设为/可挂载到根路径
secret仅在未设置BETTER_AUTH_SECRET时使用
database大多数功能必需,详见下方数据库章节
secondaryStorageRedis/KV,用于会话与限流
emailAndPassword设为{ enabled: true }激活邮箱密码登录
socialProviders例如{ google: { clientId, clientSecret }, ... }
plugins插件数组
trustedOriginsCSRF 白名单

一个带邮箱密码登录的最小配置:

import { betterAuth } from "better-auth"; export const auth = betterAuth({ appName: "My App", emailAndPassword: { enabled: true }, socialProviders: { github: { clientId: "...", clientSecret: "..." }, }, });

数据库连接与 ORM 适配器

直接连接:直接传入数据库实例即可——

import { Pool } from "pg"; // 或 mysql2 pool / better-sqlite3 / bun:sqlite export const auth = betterAuth({ database: new Pool({ connectionString: process.env.DATABASE_URL }), });

ORM 适配器:分别从better-auth/adapters/drizzle、better-auth/adapters/prisma、better-auth/adapters/mongodb导入。

关键陷阱(模型名 ≠ 表名):Better Auth 使用适配器的模型名而非底层表名。例如 Prisma 中 model 叫User、映射到表users时,配置里应写modelName: "user"(Prisma 引用名),不要写"users"。这一错误是最常见的接入失败原因之一。

会话管理

Better Auth 的会话存储遵循以下优先级:

  1. 定义了secondaryStorage→ 会话存放在 Redis/KV 中(不再进数据库)
  2. 设置session.storeSessionInDatabase: true→ 额外持久化到数据库
  3. 无数据库 +cookieCache→ 完全无状态(stateless)模式

Cookie 缓存策略

策略特点
compact(默认)Base64url + HMAC,体积最小
jwt标准 JWT,可读但已签名
jwe加密存储,安全性最高

关键会话选项

  • session.expiresIn:默认 7 天
  • session.updateAge:会话刷新间隔
  • session.cookieCache.maxAge:cookie 缓存存活时间
  • session.cookieCache.version:变更该值可使所有会话失效

配置示例:

export const auth = betterAuth({ session: { expiresIn: 60 * 60 * 24 * 7, // 7 天 updateAge: 60 * 60 * 24, // 每天刷新 cookieCache: { enabled: true, maxAge: 60 * 5, // 5 分钟 strategy: "jwt", }, }, secondaryStorage: redisStorage, // 你的 Redis 适配器 });

用户与账户配置

用户(User):user.modelName(模型名)、user.fields(列映射)、user.additionalFields(附加字段)、user.changeEmail.enabled(默认关闭)、user.deleteUser.enabled(默认关闭)。

账户(Account):account.modelName、account.accountLinking.enabled(账号关联)、account.storeAccountCookie(无状态 OAuth 场景)。

注册必需字段:email和name。

为 User 增加自定义字段:

export const auth = betterAuth({ user: { additionalFields: { plan: { type: "string", required: false }, }, }, });

邮箱流程

配置项作用
emailVerification.sendVerificationEmail必须定义,验证功能才会生效
emailVerification.sendOnSignUp/sendOnSignIn注册/登录时自动发送验证邮件
emailAndPassword.sendResetPassword密码重置邮件处理器

完整的邮箱验证配置(更深入的 email/password 流程可参考同仓库的 emailAndPassword/SKILL.md):

import { betterAuth } from "better-auth"; export const auth = betterAuth({ emailVerification: { sendOnSignUp: true, sendVerificationEmail: async ({ user, url, token }) => { await sendEmail({ to: user.email, subject: "Verify your email", text: `Click to verify: ${url}`, }); }, }, emailAndPassword: { sendResetPassword: async ({ user, url }) => { await sendEmail({ to: user.email, subject: "Reset your password", text: `Click to reset: ${url}`, }); }, }, });

安全加固

advanced 选项

选项说明
useSecureCookies强制 HTTPS Cookie
disableCSRFCheck⚠️ 安全风险,通常不建议
disableOriginCheck⚠️ 安全风险,通常不建议
crossSubDomainCookies.enabled跨子域共享 Cookie
ipAddress.ipAddressHeaders代理场景下自定义 IP 头
database.generateId自定义 ID 生成,或"serial"/"uuid"/false

限流(Rate Limiting)

export const auth = betterAuth({ rateLimit: { enabled: true, window: 60, // 窗口秒数 max: 100, // 窗口内最大请求数 storage: "secondary-storage", // "memory" | "database" | "secondary-storage" }, });

钩子(Hooks)

端点钩子

hooks.before/hooks.after是{ matcher, handler }数组,处理器用createAuthMiddleware创建。在ctx上可访问ctx.path、ctx.context.returned(after 阶段)、ctx.context.session。

数据库钩子

databaseHooks.user.create.before/after,session、account同理,适合注入默认值或执行创建后动作。

钩子上下文(ctx.context)

可用成员:session、secret、authCookies、password.hash()/password.verify()、adapter、internalAdapter、generateId()、tables、baseURL。

一个 after 钩子示例(为新建用户附加默认数据):

export const auth = betterAuth({ databaseHooks: { user: { create: { after: async (user) => { await createDefaultResources(user.id); }, }, }, }, });

插件体系

为支持 tree-shaking,插件必须从专用路径导入:

import { twoFactor } from "better-auth/plugins/two-factor"; // ✅ // import { twoFactor } from "better-auth/plugins"; // ❌

常用插件:twoFactor、organization、passkey、magicLink、emailOtp、username、phoneNumber、admin、apiKey、bearer、jwt、multiSession、sso、oauthProvider、oidcProvider、openAPI、genericOAuth。

客户端插件放进createAuthClient({ plugins: [...] })。服务端与客户端的两个完整插件示例(2FA 与组织)见同仓库的 twoFactor/SKILL.md 与 organization/SKILL.md。组合示例如下:

import { betterAuth } from "better-auth"; import { twoFactor } from "better-auth/plugins/two-factor"; import { organization } from "better-auth/plugins/organization"; export const auth = betterAuth({ appName: "My App", plugins: [twoFactor({ issuer: "My App" }), organization()], });

客户端接入

按框架从对应入口导入:

  • 原生:better-auth/client
  • React:better-auth/react
  • Vue:better-auth/vue
  • Svelte:better-auth/svelte
  • Solid:better-auth/solid
import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient(); // 登录 / 注册 / 登出 await authClient.signUp.email({ email, password, name }); await authClient.signIn.email({ email, password }); await authClient.signIn.social({ provider: "google" }); await authClient.signOut(); // 会话 const { data: session } = await authClient.getSession(); const { data } = await authClient.useSession(); // 会话撤销 await authClient.revokeSession({ token }); await authClient.revokeSessions();

类型安全

从服务端配置推断类型:

type Session = typeof auth.$Infer.Session; type SessionUser = typeof auth.$Infer.Session.user;

当客户端与服务端分属不同项目时,用泛型关联:

import { createAuthClient } from "better-auth/react"; import type { auth } from "./server/auth"; export const authClient = createAuthClient<typeof auth>();

常见陷阱(Gotchas)

  1. 模型名 vs 表名:配置使用 ORM 模型名(如user),不是数据库表名(如users)
  2. 插件 schema:新增插件后必须重新运行 CLI(migrate/generate)
  3. Secondary storage:定义了它之后,会话默认存到 KV/Redis 而非数据库
  4. Cookie 缓存:自定义 session 字段不会被缓存,总是重新获取
  5. 无状态模式:无数据库时会话只存在于 Cookie 中,缓存过期即登出
  6. 改邮箱流程:先发到当前邮箱验证,再发到新邮箱

小结与延伸阅读

本文覆盖了 Better Auth 从安装、配置、数据库、会话、邮箱、安全、钩子、插件到客户端与类型安全的完整链路。想深入具体能力,可继续阅读同仓库的关联技能文档:emailAndPassword/SKILL.md(密码策略、重置与 Argon2id)、twoFactor/SKILL.md(TOTP/OTP/备用码)与 organization/SKILL.md(多租户组织与 RBAC)。在 autoskills 中,只需npx autoskills,项目检测到better-auth依赖后即会自动安装以上全部技能,并可由 validate-registry.mjs 校验的内容确保与官方技能完全一致。

【免费下载链接】autoskills

One command. Your entire AI skill stack. Installed.

项目地址:https://gitcode.com/gh_mirrors/au/autoskills
点击查看免费下载

相关推荐

上一篇:游戏下载加速终极指南:用 Hydra 把等大作的夜晚彻底省下来
下一篇:closure-compiler与月球基地技术突破:优化地外Web应用

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询