create-auth-skill
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCreate Auth Skill
创建认证技能
Guide for adding authentication to TypeScript/JavaScript applications using Better Auth.
For code examples and syntax, see 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, or Express/Hono entry files.vite.config - Database/ORM — Look for ,
prisma/schema.prisma,drizzle.configdeps (package.json,pg,mysql2,better-sqlite3,mongoose).mongodb - Existing auth — Look for existing auth libraries (,
next-auth,lucia,clerk,supabase/auth) infirebase/author imports.package.json - Package manager — Check for ,
pnpm-lock.yaml,yarn.lock, orbun.lockb.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或 Express/Hono 入口文件。vite.config - 数据库/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 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".
AskQuestionQuestions to ask:
-
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
-
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
-
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)
-
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
-
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
-
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
-
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)
-
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
-
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
-
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需要询问的问题:
-
项目类型(如果已检测到可跳过)
- 提示:「这个项目属于什么类型?」
- 选项:从零开始的新项目 | 为现有项目添加认证 | 从其他认证库迁移
-
框架(如果已检测到可跳过)
- 提示:「你正在使用哪个框架?」
- 选项:Next.js (App Router) | Next.js (Pages Router) | SvelteKit | Nuxt | Astro | Express | Hono | SolidStart | 其他
-
数据库与 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)
-
认证方式(必须询问,允许多选)
- 提示:「你需要哪些登录方式?」
- 选项:邮箱密码 | 社交 OAuth(Google、GitHub 等) | 魔法链接(免密邮箱登录) | Passkey (WebAuthn) | 手机号
allow_multiple: true
-
社交登录提供商(仅当用户选择了社交 OAuth 时询问,在后续调用中发起)
- 提示:「你需要哪些社交登录提供商?」
- 选项:Google | GitHub | Apple | Microsoft | Discord | Twitter/X
allow_multiple: true
-
邮箱验证(仅当用户选择了邮箱密码登录时询问,在后续调用中发起)
- 提示:「是否需要强制邮箱验证?」
- 选项:是 | 否
-
邮件服务提供商(仅当用户开启了邮箱验证,或在功能中选择了密码重置时询问,在后续调用中发起)
- 提示:「你希望如何发送邮件?」
- 选项:Resend | 暂时模拟发送(输出到console.log)
-
功能与插件(必须询问,允许多选)
- 提示:「你需要哪些额外功能?」
- 选项:双因素认证 (2FA) | 组织/团队功能 | 管理后台 | API 令牌 | 密码重置 | 不需要以上功能
allow_multiple: true
-
认证页面(必须询问,允许多选,根据之前的答案预选项)
- 提示:「你需要哪些认证页面?」
- 选项根据之前的答案动态变化:
- 始终展示:登录 | 注册
- 如果选择了邮箱密码:忘记密码 | 重置密码
- 如果开启了邮箱验证:邮箱验证
allow_multiple: true
-
认证 UI 风格(必须询问)
- 提示:「你希望认证页面采用什么风格?选择一个选项或自行描述。」
- 选项:极简清爽 | 背景+居中卡片 | 分栏布局(表单+宣传图) | 浮动/玻璃拟态 | 其他(我将自行描述)
Step 3: Summarize the plan
步骤3:汇总方案
After collecting answers, present a concise implementation plan as a markdown checklist. Example:
undefined收集完所有答案后,用Markdown清单的形式展示简洁的实现方案,示例:
undefinedAuth 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
实现步骤
- Install and
better-auth@better-auth/cli - Create with server config
lib/auth.ts - Create with React client
lib/auth-client.ts - Set up route handler at
app/api/auth/[...all]/route.ts - Configure Prisma adapter and generate schema
- Add Google & GitHub OAuth providers
- Enable and
twoFactorpluginsorganization - Set up email verification handler
- Run migrations
- Create sign-in / sign-up pages
Ask the user to confirm the plan before proceeding to Phase 2.
---- 安装 和
better-auth@better-auth/cli - 创建服务端配置文件
lib/auth.ts - 创建 React 客户端配置文件
lib/auth-client.ts - 在 配置路由处理器
app/api/auth/[...all]/route.ts - 配置 Prisma 适配器并生成 schema
- 添加 Google 和 GitHub OAuth 提供商
- 开启 和
twoFactor插件organization - 配置邮箱验证处理器
- 执行数据库迁移
- 创建登录/注册页面
进入第二阶段之前需要先让用户确认方案。
---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 featuresAt 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-authScoped packages (as needed):
| Package | Use case |
|---|---|
| WebAuthn/Passkey auth |
| SAML/OIDC enterprise SSO |
| Stripe payments |
| SCIM user provisioning |
| React Native/Expo |
核心包:
npm install better-auth范围包(按需安装):
| 包名 | 适用场景 |
|---|---|
| WebAuthn/Passkey 认证 |
| SAML/OIDC 企业级 SSO |
| Stripe 支付集成 |
| SCIM 用户 provisioning |
| 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: , , , etc.
GITHUB_CLIENT_IDGITHUB_CLIENT_SECRETGOOGLE_CLIENT_IDenv
BETTER_AUTH_SECRET=<32位以上字符,可通过 openssl rand -base64 32 生成>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=<你的数据库连接字符串>按需添加OAuth密钥:、、 等。
GITHUB_CLIENT_IDGITHUB_CLIENT_SECRETGOOGLE_CLIENT_IDServer Config (auth.ts)
服务端配置 (auth.ts)
Location: or
lib/auth.tssrc/lib/auth.tsMinimal config needs:
- - Connection or adapter
database - - For email/password auth
emailAndPassword: { enabled: true }
Standard config adds:
- - OAuth providers (google, github, etc.)
socialProviders - - Email verification handler
emailVerification.sendVerificationEmail - - Password reset handler
emailAndPassword.sendResetPassword
Full config adds:
- - Array of feature plugins
plugins - - Expiry, cookie cache settings
session - - Multi-provider linking
account.accountLinking - - Rate limiting config
rateLimit
Export types:
export type Session = typeof auth.$Infer.Session存放位置: 或
lib/auth.tssrc/lib/auth.ts最小配置要求:
- - 连接或适配器
database - - 开启邮箱密码认证
emailAndPassword: { enabled: true }
标准配置额外添加:
- - OAuth 提供商(google、github 等)
socialProviders - - 邮箱验证处理器
emailVerification.sendVerificationEmail - - 密码重置处理器
emailAndPassword.sendResetPassword
完整配置额外添加:
- - 功能插件数组
plugins - - 过期时间、Cookie缓存设置
session - - 多提供商账号关联
account.accountLinking - - 限流配置
rateLimit
导出类型:
export type Session = typeof auth.$Infer.SessionClient Config (auth-client.ts)
客户端配置 (auth-client.ts)
Import by framework:
| Framework | Import |
|---|---|
| React/Next.js | |
| Vue | |
| Svelte | |
| Solid | |
| Vanilla JS | |
Client plugins go in .
createAuthClient({ plugins: [...] })Common exports: , , , ,
signInsignUpsignOutuseSessiongetSession按框架导入:
| 框架 | 导入路径 |
|---|---|
| React/Next.js | |
| Vue | |
| Svelte | |
| Solid | |
| 原生 JS | |
客户端插件配置在 中。
createAuthClient({ plugins: [...] })常用导出: 、、、、
signInsignUpsignOutuseSessiongetSessionRoute Handler Setup
路由处理器配置
| Framework | File | Handler |
|---|---|---|
| Next.js App Router | | |
| Next.js Pages | | |
| Express | Any file | |
| SvelteKit | | |
| SolidStart | Route file | |
| Hono | Route file | |
Next.js Server Components: Add plugin to auth config.
nextCookies()| 框架 | 文件路径 | 处理器 |
|---|---|---|
| Next.js App Router | | |
| Next.js Pages | | |
| Express | 任意文件 | |
| SvelteKit | | |
| SolidStart | 路由文件 | |
| Hono | 路由文件 | |
Next.js 服务端组件: 在认证配置中添加 插件。
nextCookies()Database Migrations
数据库迁移
| Adapter | Command |
|---|---|
| Built-in Kysely | |
| Prisma | |
| Drizzle | |
Re-run after adding plugins.
| 适配器 | 命令 |
|---|---|
| 内置 Kysely | |
| Prisma | |
| Drizzle | |
添加插件后需要重新执行迁移。
Database Adapters
数据库适配器
| Database | Setup |
|---|---|
| SQLite | Pass |
| PostgreSQL | Pass |
| MySQL | Pass |
| Prisma | |
| Drizzle | |
| MongoDB | |
| 数据库 | 配置方式 |
|---|---|
| SQLite | 直接传入 |
| PostgreSQL | 直接传入 |
| MySQL | 直接传入 |
| Prisma | 从 |
| Drizzle | 从 |
| MongoDB | 从 |
Common Plugins
常用插件
| Plugin | Server Import | Client Import | Purpose |
|---|---|---|---|
| | | 2FA with TOTP/OTP |
| | | Teams/orgs |
| | | User management |
| | - | API token auth |
| | - | API docs |
| | | WebAuthn |
| | - | Enterprise SSO |
Plugin pattern: Server plugin + client plugin + run migrations.
| 插件名称 | 服务端导入路径 | 客户端导入 | 用途 |
|---|---|---|---|
| | | 基于 TOTP/OTP 的双因素认证 |
| | | 团队/组织功能 |
| | | 用户管理 |
| | - | API 令牌认证 |
| | - | API 文档 |
| | | WebAuthn 认证 |
| | - | 企业级 SSO |
插件使用模式: 服务端插件 + 客户端插件 + 执行数据库迁移。
Auth UI Implementation
认证 UI 实现
Sign in flow:
- or
signIn.email({ email, password })signIn.social({ provider, callbackURL }) - Handle in response
error - Redirect on success
Session check (client): hook returns
useSession(){ data: session, isPending }Session check (server):
auth.api.getSession({ headers: await headers() })Protected routes: Check session, redirect to if null.
/sign-in登录流程:
- 调用 或
signIn.email({ email, password })signIn.social({ provider, callbackURL }) - 处理响应中的
error - 成功后重定向
客户端会话检查: 钩子返回
useSession(){ data: session, isPending }服务端会话检查:
auth.api.getSession({ headers: await headers() })受保护路由: 检查会话,如果为空则重定向到 。
/sign-inSecurity Checklist
安全检查清单
- set (32+ chars)
BETTER_AUTH_SECRET - in production
advanced.useSecureCookies: true - configured
trustedOrigins - Rate limits enabled
- Email verification enabled
- Password reset implemented
- 2FA for sensitive apps
- CSRF protection NOT disabled
- reviewed
account.accountLinking
- 已设置 (32位以上字符)
BETTER_AUTH_SECRET - 生产环境开启
advanced.useSecureCookies: true - 已配置
trustedOrigins - 已开启限流
- 已开启邮箱验证
- 已实现密码重置功能
- 敏感应用已开启 2FA
- 未禁用 CSRF 保护
- 已审核 配置
account.accountLinking
Troubleshooting
故障排除
| Issue | Fix |
|---|---|
| "Secret not set" | Add |
| "Invalid Origin" | Add domain to |
| Cookies not setting | Check |
| OAuth callback errors | Verify redirect URIs in provider dashboard |
| Type errors after adding plugin | Re-run CLI generate/migrate |
| 问题 | 解决方案 |
|---|---|
| "Secret not set" | 添加 |
| "Invalid Origin" | 将域名添加到 |
| Cookie 未设置 | 检查 |
| OAuth 回调错误 | 验证提供商后台的重定向URI配置 |
| 添加插件后出现类型错误 | 重新执行CLI生成/迁移命令 |