Skip to content
create-auth-skill logo

Create Auth Skill

create-auth-skill

使用 Better Auth 为 TypeScript/JavaScript 应用创建鉴权层的技能。

SKILL.md

Full skill instructions

Create Auth Skill

使用 Better Auth 为 TypeScript/​JavaScript 应用添加鉴权的指南。

代码示例与语法参见 better-auth.com/​docs。


决策树

是否为新项目/空项目?
├─ 是 → 新项目搭建
│ 1. 确定框架
│ 2. 选择数据库
│ 3. 安装 better-auth
│ 4. 创建 auth.ts + auth-client.ts
│ 5. 配置路由处理器
│ 6. 运行 CLI migrate/​generate
│ 7. 通过插件添加能力
│
└─ 否 → 项目是否已有鉴权?
 ├─ 是 → 迁移/增强
 │ • 审计现有鉴权缺口
 │ • 规划渐进式迁移
 │ • 参考文档中的迁移指南
 │
 └─ 否 → 为现有项目添加鉴权
 1. 分析项目结构
 2. 安装 better-auth
 3. 创建 auth 配置
 4. 添加路由处理器
 5. 运行 schema 迁移
 6. 接入现有页面

安装

核心: npm install better-auth

按需安装的作用域包:

包用途
@better-auth/​passkeyWebAuthn/​Passkey 鉴权
@better-auth/​ssoSAML/​OIDC 企业 SSO
@better-auth/​stripeStripe 支付
@better-auth/​scimSCIM 用户配置
@better-auth/​expoReact Native/​Expo

环境变量

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 等。


服务端配置(auth.ts)

位置: 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


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

按框架导入:

框架导入
React/​Next.jsbetter-auth/​react
Vuebetter-auth/​vue
Sveltebetter-auth/​svelte
Solidbetter-auth/​solid
Vanilla JSbetter-auth/​client

客户端插件 放在 createAuthClient({ plugins: [...] }) 中。

常用导出: signIn、signUp、signOut、useSession、getSession


路由处理器配置

框架文件处理器
Next.js App Routerapp/​api/​auth/[...all]/​route.tstoNextJsHandler(auth) → 导出 { GET, POST }
Next.js Pagespages/​api/​auth/[...all].tstoNextJsHandler(auth) → 默认导出
Express任意文件app.all("/​api/​auth/​*", toNodeHandler(auth))
SvelteKitsrc/​hooks.server.tssvelteKitHandler(auth)
SolidStart路由文件solidStartHandler(auth)
Hono路由文件auth.handler(c.req.raw)

Next.js Server Components: 在 auth 配置中添加 nextCookies() 插件。


数据库迁移

适配器命令
内置 Kyselynpx @better-auth/​cli@latest migrate(直接应用)
Prismanpx @better-auth/​cli@latest generate --output prisma/​schema.prisma 然后 npx prisma migrate dev
Drizzlenpx @better-auth/​cli@latest generate --output src/​db/​auth-schema.ts 然后 npx drizzle-kit push

添加插件后需重新执行。


数据库适配器

数据库配置
SQLite直接传入 better-sqlite3 或 bun:sqlite 实例
PostgreSQL直接传入 pg.Pool 实例
MySQL直接传入 mysql2 pool
PrismaprismaAdapter(prisma, { provider: "postgresql" }),来自 better-auth/​adapters/​prisma
DrizzledrizzleAdapter(db, { provider: "pg" }),来自 better-auth/​adapters/​drizzle
MongoDBmongodbAdapter(db),来自 better-auth/​adapters/​mongodb

常用插件

插件服务端导入客户端导入用途
twoFactorbetter-auth/​pluginstwoFactorClientTOTP/​OTP 双因素
organizationbetter-auth/​pluginsorganizationClient团队/组织
adminbetter-auth/​pluginsadminClient用户管理
bearerbetter-auth/​plugins-API Token 鉴权
openAPIbetter-auth/​plugins-API 文档
passkey@better-auth/​passkeypasskeyClientWebAuthn
sso@better-auth/​sso-企业 SSO

插件用法: 服务端插件 + 客户端插件 + 执行迁移。


鉴权 UI 实现

登录流程:

  1. signIn.email({ email, password }) 或 signIn.social({ provider, callbackURL })
  2. 处理返回的 error
  3. 成功时重定向

客户端会话检查: useSession() 返回 { data: session, isPending }

服务端会话检查: auth.api.getSession({ headers: await headers() })

受保护路由: 检查 session,为空则重定向到 /​sign-in。


安全清单

  • 设置 BETTER_AUTH_SECRET(32+ 字符)
  • 生产环境启用 advanced.useSecureCookies: true
  • 配置 trustedOrigins
  • 启用限流
  • 启用邮箱验证
  • 实现密码重置
  • 敏感应用启用 2FA
  • 不要关闭 CSRF 防护
  • 审查 account.accountLinking

故障排查

问题处理
"Secret not set"添加 BETTER_AUTH_SECRET 环境变量
"Invalid Origin"在 trustedOrigins 中加入域名
Cookie 不生效检查 baseURL 与域名一致;生产启用 secure cookies
OAuth 回调错误在提供方控制台核对 redirect URIs
添加插件后类型报错重新运行 CLI generate/​migrate

参考

More skills from diegosouzapw

accessibility logo
diegosouzapw/awesome-omni-skill

accessibility

Accessibility guidelines for VS Code features — covers accessibility help dialogs, accessible views, verbosity settings, accessibility signals, ARIA alerts/status announcements, keyboard navigation, and ARIA labels/roles. Applies to both new interactive UI surfaces and updates to existing feature...

62 1
View
mermaid-diagrams logo
diegosouzapw/awesome-omni-skill

mermaid-diagrams

Mermaid diagram creation for flowcharts, sequences, ERDs, and more. Generate diagrams from text in markdown files. Use for documentation, architecture diagrams, and visual representations. Triggers on mermaid, flowchart, sequence diagram, ERD, entity relationship, gantt chart, pie chart, class di...

62 1
View
tauri2-react-rust logo
diegosouzapw/awesome-omni-skill

tauri2-react-rust

Guides development of cross-platform desktop apps with Tauri 2, TypeScript, React, and Rust. Use when building Tauri apps, implementing IPC, designing Rust backend or TypeScript/React frontend, when researching or cloning a website (open site, snapshot elements), when verifying local dev or built...

62 1
View
fp-ts-errors logo
diegosouzapw/awesome-omni-skill

fp-ts-errors

Handle errors as values using fp-ts Either and TaskEither for cleaner, more predictable TypeScript code. Use when implementing error handling patterns with fp-ts.

62 0
View
ring:pre-dev-research logo
diegosouzapw/awesome-omni-skill

ring:pre-dev-research

Gate 0 research phase for pre-dev workflow. Dispatches 3 parallel research agents to gather codebase patterns, external best practices, and framework documentation BEFORE creating PRD/TRD. Outputs research.md with file:line references.

62 0
View
create-assistant logo
diegosouzapw/awesome-omni-skill

create-assistant

Create and configure Vapi voice AI assistants with models, voices, transcribers, tools, hooks, and advanced settings. Use when building voice agents, phone bots, customer support assistants, or any conversational AI that handles phone or web calls.

62 0
View
codex-headless logo
diegosouzapw/awesome-omni-skill

codex-headless

Delegiere Aufgaben an OpenAI Codex CLI im Headless-Mode. Nutzt ChatGPT Subscription (KEIN API Key). Nur Workspace-Zugriff, KEIN System-Zugriff. Auto-Accept mit --full-auto. Web-Recherche mit --search.

62 0
View
social-media-scheduler logo
diegosouzapw/awesome-omni-skill

social-media-scheduler

Generate a full week of social media content for any topic. Outputs platform-optimized posts for Twitter/X, LinkedIn, and Instagram with hashtags and posting times.

62 0
View
Data Privacy Compliance logo
diegosouzapw/awesome-omni-skill

Data Privacy Compliance

Data privacy and regulatory compliance specialist for GDPR, CCPA, HIPAA, and international data protection laws. Use when implementing privacy controls, conducting data protection impact assessments, ensuring regulatory compliance, or managing data subject rights. Expert in consent management, da...

62 0
View
triple-review logo
diegosouzapw/awesome-omni-skill

triple-review

Reviews a task using the TRIPLE protocol, as the review agent.

62 0
View
Tech Stack & Architecture Decision logo
diegosouzapw/awesome-omni-skill

Tech Stack & Architecture Decision

Define and document the technology stack and architecture decisions for a project. Use when the user needs to choose a tech stack, make architecture decisions, define infrastructure choices, or document technology selections. Triggers on requests like "define the tech stack", "choose technologies...

62 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View