create-auth-skill

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Create Auth Skill

创建认证技能

Guide for adding authentication to TypeScript/JavaScript applications using Better Auth.
For code examples and syntax, see better-auth.com/docs.

使用 Better Auth 为 TypeScript/JavaScript 应用添加身份认证的指南。
代码示例和语法请参考 better-auth.com/docs

Phase 1: Planning (REQUIRED before implementation)

第一阶段:规划(实现前必须完成)

Before writing any code, gather requirements by scanning the project and asking the user structured questions. This ensures the implementation matches their needs.
编写任何代码之前,先扫描项目并向用户询问结构化问题来收集需求,确保实现方案符合用户预期。

Step 1: Scan the project

步骤1:扫描项目

Analyze the codebase to auto-detect:
  • Framework — Look for
    next.config
    ,
    svelte.config
    ,
    nuxt.config
    ,
    astro.config
    ,
    vite.config
    , or Express/Hono entry files.
  • Database/ORM — Look for
    prisma/schema.prisma
    ,
    drizzle.config
    ,
    package.json
    deps (
    pg
    ,
    mysql2
    ,
    better-sqlite3
    ,
    mongoose
    ,
    mongodb
    ).
  • Existing auth — Look for existing auth libraries (
    next-auth
    ,
    lucia
    ,
    clerk
    ,
    supabase/auth
    ,
    firebase/auth
    ) in
    package.json
    or imports.
  • Package manager — Check for
    pnpm-lock.yaml
    ,
    yarn.lock
    ,
    bun.lockb
    , or
    package-lock.json
    .
Use what you find to pre-fill defaults and skip questions you can already answer.
分析代码库自动检测以下信息:
  • 框架 — 查找
    next.config
    svelte.config
    nuxt.config
    astro.config
    vite.config
    或 Express/Hono 入口文件。
  • 数据库/ORM — 查找
    prisma/schema.prisma
    drizzle.config
    package.json
    依赖项(
    pg
    mysql2
    better-sqlite3
    mongoose
    mongodb
    )。
  • 现有认证方案 — 查找
    package.json
    或导入语句中是否包含现有认证库(
    next-auth
    lucia
    clerk
    supabase/auth
    firebase/auth
    )。
  • 包管理器 — 检查是否存在
    pnpm-lock.yaml
    yarn.lock
    bun.lockb
    package-lock.json
使用扫描到的信息预填默认值,跳过已经可以确定答案的问题。

Step 2: Ask planning questions

步骤2:询问规划相关问题

Use the
AskQuestion
tool to ask the user all applicable questions in a single call. Skip any question you already have a confident answer for from the scan. Group them under a title like "Auth Setup Planning".
Questions to ask:
  1. Project type (skip if detected)
    • Prompt: "What type of project is this?"
    • Options: New project from scratch | Adding auth to existing project | Migrating from another auth library
  2. Framework (skip if detected)
    • Prompt: "Which framework are you using?"
    • Options: Next.js (App Router) | Next.js (Pages Router) | SvelteKit | Nuxt | Astro | Express | Hono | SolidStart | Other
  3. Database & ORM (skip if detected)
    • Prompt: "Which database setup will you use?"
    • Options: PostgreSQL (Prisma) | PostgreSQL (Drizzle) | PostgreSQL (pg driver) | MySQL (Prisma) | MySQL (Drizzle) | MySQL (mysql2 driver) | SQLite (Prisma) | SQLite (Drizzle) | SQLite (better-sqlite3 driver) | MongoDB (Mongoose) | MongoDB (native driver)
  4. Authentication methods (always ask, allow multiple)
    • Prompt: "Which sign-in methods do you need?"
    • Options: Email & password | Social OAuth (Google, GitHub, etc.) | Magic link (passwordless email) | Passkey (WebAuthn) | Phone number
    • allow_multiple: true
  5. Social providers (only if they selected Social OAuth above — ask in a follow-up call)
    • Prompt: "Which social providers do you need?"
    • Options: Google | GitHub | Apple | Microsoft | Discord | Twitter/X
    • allow_multiple: true
  6. Email verification (only if Email & password was selected above — ask in a follow-up call)
    • Prompt: "Do you want to require email verification?"
    • Options: Yes | No
  7. Email provider (only if email verification is Yes, or if Password reset is selected in features — ask in a follow-up call)
    • Prompt: "How do you want to send emails?"
    • Options: Resend | Mock it for now (console.log)
  8. Features & plugins (always ask, allow multiple)
    • Prompt: "Which additional features do you need?"
    • Options: Two-factor authentication (2FA) | Organizations / teams | Admin dashboard | API bearer tokens | Password reset | None of these
    • allow_multiple: true
  9. Auth pages (always ask, allow multiple — pre-select based on earlier answers)
    • Prompt: "Which auth pages do you need?"
    • Options vary based on previous answers:
      • Always available: Sign in | Sign up
      • If Email & password selected: Forgot password | Reset password
      • If email verification enabled: Email verification
    • allow_multiple: true
  10. Auth UI style (always ask)
  • Prompt: "What style do you want for the auth pages? Pick one or describe your own."
  • Options: Minimal & clean | Centered card with background | Split layout (form + hero image) | Floating / glassmorphism | Other (I'll describe)
使用
AskQuestion
工具单次调用询问所有适用的问题,跳过通过扫描已经可以明确答案的问题,将问题归类在「认证设置规划」的标题下。
需要询问的问题:
  1. 项目类型(如果已检测到可跳过)
    • 提示:「这个项目属于什么类型?」
    • 选项:从零开始的新项目 | 为现有项目添加认证 | 从其他认证库迁移
  2. 框架(如果已检测到可跳过)
    • 提示:「你正在使用哪个框架?」
    • 选项:Next.js (App Router) | Next.js (Pages Router) | SvelteKit | Nuxt | Astro | Express | Hono | SolidStart | 其他
  3. 数据库与 ORM(如果已检测到可跳过)
    • 提示:「你将使用哪种数据库配置?」
    • 选项:PostgreSQL (Prisma) | PostgreSQL (Drizzle) | PostgreSQL (pg driver) | MySQL (Prisma) | MySQL (Drizzle) | MySQL (mysql2 driver) | SQLite (Prisma) | SQLite (Drizzle) | SQLite (better-sqlite3 driver) | MongoDB (Mongoose) | MongoDB (native driver)
  4. 认证方式(必须询问,允许多选)
    • 提示:「你需要哪些登录方式?」
    • 选项:邮箱密码 | 社交 OAuth(Google、GitHub 等) | 魔法链接(免密邮箱登录) | Passkey (WebAuthn) | 手机号
    • allow_multiple: true
  5. 社交登录提供商(仅当用户选择了社交 OAuth 时询问,在后续调用中发起)
    • 提示:「你需要哪些社交登录提供商?」
    • 选项:Google | GitHub | Apple | Microsoft | Discord | Twitter/X
    • allow_multiple: true
  6. 邮箱验证(仅当用户选择了邮箱密码登录时询问,在后续调用中发起)
    • 提示:「是否需要强制邮箱验证?」
    • 选项:是 | 否
  7. 邮件服务提供商(仅当用户开启了邮箱验证,或在功能中选择了密码重置时询问,在后续调用中发起)
    • 提示:「你希望如何发送邮件?」
    • 选项:Resend | 暂时模拟发送(输出到console.log)
  8. 功能与插件(必须询问,允许多选)
    • 提示:「你需要哪些额外功能?」
    • 选项:双因素认证 (2FA) | 组织/团队功能 | 管理后台 | API 令牌 | 密码重置 | 不需要以上功能
    • allow_multiple: true
  9. 认证页面(必须询问,允许多选,根据之前的答案预选项)
    • 提示:「你需要哪些认证页面?」
    • 选项根据之前的答案动态变化:
      • 始终展示:登录 | 注册
      • 如果选择了邮箱密码:忘记密码 | 重置密码
      • 如果开启了邮箱验证:邮箱验证
    • allow_multiple: true
  10. 认证 UI 风格(必须询问)
    • 提示:「你希望认证页面采用什么风格?选择一个选项或自行描述。」
    • 选项:极简清爽 | 背景+居中卡片 | 分栏布局(表单+宣传图) | 浮动/玻璃拟态 | 其他(我将自行描述)

Step 3: Summarize the plan

步骤3:汇总方案

After collecting answers, present a concise implementation plan as a markdown checklist. Example:
undefined
收集完所有答案后,用Markdown清单的形式展示简洁的实现方案,示例:
undefined

Auth Implementation Plan

认证实现方案

  • Framework: Next.js (App Router)
  • Database: PostgreSQL via Prisma
  • Auth methods: Email/password, Google OAuth, GitHub OAuth
  • Plugins: 2FA, Organizations, Email verification
  • UI: Custom forms
  • 框架: Next.js (App Router)
  • 数据库: PostgreSQL + Prisma
  • 认证方式: 邮箱密码、Google OAuth、GitHub OAuth
  • 插件: 2FA、组织功能、邮箱验证
  • UI: 自定义表单

Steps

实现步骤

  1. Install
    better-auth
    and
    @better-auth/cli
  2. Create
    lib/auth.ts
    with server config
  3. Create
    lib/auth-client.ts
    with React client
  4. Set up route handler at
    app/api/auth/[...all]/route.ts
  5. Configure Prisma adapter and generate schema
  6. Add Google & GitHub OAuth providers
  7. Enable
    twoFactor
    and
    organization
    plugins
  8. Set up email verification handler
  9. Run migrations
  10. Create sign-in / sign-up pages

Ask the user to confirm the plan before proceeding to Phase 2.

---
  1. 安装
    better-auth
    @better-auth/cli
  2. 创建服务端配置文件
    lib/auth.ts
  3. 创建 React 客户端配置文件
    lib/auth-client.ts
  4. app/api/auth/[...all]/route.ts
    配置路由处理器
  5. 配置 Prisma 适配器并生成 schema
  6. 添加 Google 和 GitHub OAuth 提供商
  7. 开启
    twoFactor
    organization
    插件
  8. 配置邮箱验证处理器
  9. 执行数据库迁移
  10. 创建登录/注册页面

进入第二阶段之前需要先让用户确认方案。

---

Phase 2: Implementation

第二阶段:实现

Only proceed here after the user confirms the plan from Phase 1.
Follow the decision tree below, guided by the answers collected above.
Is this a new/empty project?
├─ YES → New project setup
│   1. Install better-auth (+ scoped packages per plan)
│   2. Create auth.ts with all planned config
│   3. Create auth-client.ts with framework client
│   4. Set up route handler
│   5. Set up environment variables
│   6. Run CLI migrate/generate
│   7. Add plugins from plan
│   8. Create auth UI pages
├─ MIGRATING → Migration from existing auth
│   1. Audit current auth for gaps
│   2. Plan incremental migration
│   3. Install better-auth alongside existing auth
│   4. Migrate routes, then session logic, then UI
│   5. Remove old auth library
│   6. See migration guides in docs
└─ ADDING → Add auth to existing project
    1. Analyze project structure
    2. Install better-auth
    3. Create auth config matching plan
    4. Add route handler
    5. Run schema migrations
    6. Integrate into existing pages
    7. Add planned plugins and features
At the end of implementation, guide users thoroughly on remaining next steps (e.g., setting up OAuth app credentials, deploying env vars, testing flows).

仅当用户确认第一阶段的方案后再进入本阶段。
根据之前收集的答案,按照以下决策树执行:
是否为全新/空项目?
├─ 是 → 新项目搭建
│   1. 安装 better-auth(以及方案中指定的范围包)
│   2. 创建包含所有规划配置的 auth.ts
│   3. 创建对应框架的 auth-client.ts
│   4. 配置路由处理器
│   5. 配置环境变量
│   6. 运行CLI迁移/生成命令
│   7. 添加方案中指定的插件
│   8. 创建认证 UI 页面
├─ 迁移 → 从现有认证方案迁移
│   1. 审计现有认证方案的差异
│   2. 制定渐进式迁移方案
│   3. 与现有认证方案并行安装 better-auth
│   4. 先迁移路由,再迁移会话逻辑,最后迁移UI
│   5. 移除旧的认证库
│   6. 参考文档中的迁移指南
└─ 新增 → 为现有项目添加认证
    1. 分析项目结构
    2. 安装 better-auth
    3. 创建符合方案的认证配置
    4. 添加路由处理器
    5. 执行 schema 迁移
    6. 集成到现有页面
    7. 添加方案中指定的插件和功能
实现完成后,要详细引导用户完成剩余的后续步骤(例如配置OAuth应用凭据、部署环境变量、测试流程等)。

Installation

安装

Core:
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/scim
SCIM user provisioning
@better-auth/expo
React Native/Expo

核心包:
npm install better-auth
范围包(按需安装):
包名适用场景
@better-auth/passkey
WebAuthn/Passkey 认证
@better-auth/sso
SAML/OIDC 企业级 SSO
@better-auth/stripe
Stripe 支付集成
@better-auth/scim
SCIM 用户 provisioning
@better-auth/expo
React Native/Expo 开发

Environment Variables

环境变量

env
BETTER_AUTH_SECRET=<32+ chars, generate with: openssl rand -base64 32>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<your database connection string>
Add OAuth secrets as needed:
GITHUB_CLIENT_ID
,
GITHUB_CLIENT_SECRET
,
GOOGLE_CLIENT_ID
, etc.

env
BETTER_AUTH_SECRET=<32位以上字符,可通过 openssl rand -base64 32 生成>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<你的数据库连接字符串>
按需添加OAuth密钥:
GITHUB_CLIENT_ID
GITHUB_CLIENT_SECRET
GOOGLE_CLIENT_ID
等。

Server Config (auth.ts)

服务端配置 (auth.ts)

Location:
lib/auth.ts
or
src/lib/auth.ts
Minimal config needs:
  • database
    - Connection or adapter
  • emailAndPassword: { enabled: true }
    - For email/password auth
Standard config adds:
  • socialProviders
    - OAuth providers (google, github, etc.)
  • emailVerification.sendVerificationEmail
    - Email verification handler
  • emailAndPassword.sendResetPassword
    - Password reset handler
Full config adds:
  • plugins
    - Array of feature plugins
  • session
    - Expiry, cookie cache settings
  • account.accountLinking
    - Multi-provider linking
  • rateLimit
    - Rate limiting config
Export types:
export type Session = typeof auth.$Infer.Session

存放位置:
lib/auth.ts
src/lib/auth.ts
最小配置要求:
  • database
    - 连接或适配器
  • emailAndPassword: { enabled: true }
    - 开启邮箱密码认证
标准配置额外添加:
  • socialProviders
    - OAuth 提供商(google、github 等)
  • emailVerification.sendVerificationEmail
    - 邮箱验证处理器
  • emailAndPassword.sendResetPassword
    - 密码重置处理器
完整配置额外添加:
  • plugins
    - 功能插件数组
  • session
    - 过期时间、Cookie缓存设置
  • account.accountLinking
    - 多提供商账号关联
  • rateLimit
    - 限流配置
导出类型:
export type Session = typeof auth.$Infer.Session

Client Config (auth-client.ts)

客户端配置 (auth-client.ts)

Import by framework:
FrameworkImport
React/Next.js
better-auth/react
Vue
better-auth/vue
Svelte
better-auth/svelte
Solid
better-auth/solid
Vanilla JS
better-auth/client
Client plugins go in
createAuthClient({ plugins: [...] })
.
Common exports:
signIn
,
signUp
,
signOut
,
useSession
,
getSession

按框架导入:
框架导入路径
React/Next.js
better-auth/react
Vue
better-auth/vue
Svelte
better-auth/svelte
Solid
better-auth/solid
原生 JS
better-auth/client
客户端插件配置在
createAuthClient({ plugins: [...] })
中。
常用导出:
signIn
signUp
signOut
useSession
getSession

Route Handler Setup

路由处理器配置

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 file
app.all("/api/auth/*", toNodeHandler(auth))
SvelteKit
src/hooks.server.ts
svelteKitHandler(auth)
SolidStartRoute file
solidStartHandler(auth)
HonoRoute file
auth.handler(c.req.raw)
Next.js Server Components: Add
nextCookies()
plugin to auth config.

框架文件路径处理器
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/*", toNodeHandler(auth))
SvelteKit
src/hooks.server.ts
svelteKitHandler(auth)
SolidStart路由文件
solidStartHandler(auth)
Hono路由文件
auth.handler(c.req.raw)
Next.js 服务端组件: 在认证配置中添加
nextCookies()
插件。

Database Migrations

数据库迁移

AdapterCommand
Built-in Kysely
npx @better-auth/cli@latest migrate
(applies directly)
Prisma
npx @better-auth/cli@latest generate --output prisma/schema.prisma
then
npx prisma migrate dev
Drizzle
npx @better-auth/cli@latest generate --output src/db/auth-schema.ts
then
npx drizzle-kit push
Re-run after adding plugins.

适配器命令
内置 Kysely
npx @better-auth/cli@latest migrate
(直接执行迁移)
Prisma
npx @better-auth/cli@latest generate --output prisma/schema.prisma
然后执行
npx prisma migrate dev
Drizzle
npx @better-auth/cli@latest generate --output src/db/auth-schema.ts
然后执行
npx drizzle-kit push
添加插件后需要重新执行迁移。

Database Adapters

数据库适配器

DatabaseSetup
SQLitePass
better-sqlite3
or
bun:sqlite
instance directly
PostgreSQLPass
pg.Pool
instance directly
MySQLPass
mysql2
pool directly
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

数据库配置方式
SQLite直接传入
better-sqlite3
bun:sqlite
实例
PostgreSQL直接传入
pg.Pool
实例
MySQL直接传入
mysql2
pool 实例
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)

Common Plugins

常用插件

PluginServer ImportClient ImportPurpose
twoFactor
better-auth/plugins
twoFactorClient
2FA with TOTP/OTP
organization
better-auth/plugins
organizationClient
Teams/orgs
admin
better-auth/plugins
adminClient
User management
bearer
better-auth/plugins
-API token auth
openAPI
better-auth/plugins
-API docs
passkey
@better-auth/passkey
passkeyClient
WebAuthn
sso
@better-auth/sso
-Enterprise SSO
Plugin pattern: Server plugin + client plugin + run migrations.

插件名称服务端导入路径客户端导入用途
twoFactor
better-auth/plugins
twoFactorClient
基于 TOTP/OTP 的双因素认证
organization
better-auth/plugins
organizationClient
团队/组织功能
admin
better-auth/plugins
adminClient
用户管理
bearer
better-auth/plugins
-API 令牌认证
openAPI
better-auth/plugins
-API 文档
passkey
@better-auth/passkey
passkeyClient
WebAuthn 认证
sso
@better-auth/sso
-企业级 SSO
插件使用模式: 服务端插件 + 客户端插件 + 执行数据库迁移。

Auth UI Implementation

认证 UI 实现

Sign in flow:
  1. signIn.email({ email, password })
    or
    signIn.social({ provider, callbackURL })
  2. Handle
    error
    in response
  3. Redirect on success
Session check (client):
useSession()
hook returns
{ data: session, isPending }
Session check (server):
auth.api.getSession({ headers: await headers() })
Protected routes: Check session, redirect to
/sign-in
if null.

登录流程:
  1. 调用
    signIn.email({ email, password })
    signIn.social({ provider, callbackURL })
  2. 处理响应中的
    error
  3. 成功后重定向
客户端会话检查:
useSession()
钩子返回
{ data: session, isPending }
服务端会话检查:
auth.api.getSession({ headers: await headers() })
受保护路由: 检查会话,如果为空则重定向到
/sign-in

Security Checklist

安全检查清单

  • BETTER_AUTH_SECRET
    set (32+ chars)
  • advanced.useSecureCookies: true
    in production
  • trustedOrigins
    configured
  • Rate limits enabled
  • Email verification enabled
  • Password reset implemented
  • 2FA for sensitive apps
  • CSRF protection NOT disabled
  • account.accountLinking
    reviewed

  • 已设置
    BETTER_AUTH_SECRET
    (32位以上字符)
  • 生产环境开启
    advanced.useSecureCookies: true
  • 已配置
    trustedOrigins
  • 已开启限流
  • 已开启邮箱验证
  • 已实现密码重置功能
  • 敏感应用已开启 2FA
  • 未禁用 CSRF 保护
  • 已审核
    account.accountLinking
    配置

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
Type errors after adding pluginRe-run CLI generate/migrate

问题解决方案
"Secret not set"添加
BETTER_AUTH_SECRET
环境变量
"Invalid Origin"将域名添加到
trustedOrigins
Cookie 未设置检查
baseURL
是否与域名匹配;生产环境开启安全Cookie
OAuth 回调错误验证提供商后台的重定向URI配置
添加插件后出现类型错误重新执行CLI生成/迁移命令

Resources

参考资源