Better Auth 认证授权
better-auth
使用 Better Auth(一个与框架无关的 TypeScript 认证框架)实现认证与授权。功能包括:带验证的邮箱/密码认证、OAuth 提供商(Google、GitHub、Discord 等)、双因素认证(TOTP、短信)、通行密钥(Passkey)/WebAuthn 支持、会话管理、基于角色的访问控制(RBAC)、速率限制以及数据库适配器。用于为应用添加认证、实现 OAuth 流程、配置 2FA/MFA、管理用户会话、配置授权规则,或为 Web 应用构建安全的认证系统。
- License 许可
- MIT
- 最近更新
- 2026-08-27
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- better-auth
- license
- MIT
- version
- 2.0.0
- description
- Implement authentication and authorization with Better Auth - a framework-agnostic TypeScript authentication framework. Features include email/password authentication with verification, OAuth providers (Google, GitHub, Discord, etc.), two-factor authentication (TOTP, SMS), passkeys/WebAuthn support, session management, role-based access control (RBAC), rate limiting, and database adapters. Use when adding authentication to applications, implementing OAuth flows, setting up 2FA/MFA, managing user sessions, configuring authorization rules, or building secure authentication systems for web applications.
02 资源文件 13
- 参考文档references/advanced-features.md10.4 KB
- 参考文档references/database-integration.md10.3 KB
- 参考文档references/email-password-auth.md8.4 KB
- 参考文档references/oauth-providers.md9.1 KB
- 参考文档resources/integration-testing.md13.7 KB
- 参考文档resources/local-setup.md11.8 KB
- 参考文档resources/replay-testing.md12.5 KB
- 参考文档resources/unit-testing.md9.3 KB
- 脚本scripts/.coverage52.0 KB
- 脚本scripts/better_auth_init.py16.0 KB
- 脚本scripts/requirements.txt402 B
- 脚本scripts/tests/.coverage52.0 KB
- 脚本scripts/tests/test_better_auth_init.py15.1 KB
03 SKILL.md 正文
Better Auth Skill
Better Auth is comprehensive, framework-agnostic authentication/authorization framework for TypeScript with built-in email/password, social OAuth, and powerful plugin ecosystem for advanced features.
When to Use
- Implementing auth in TypeScript/JavaScript applications
- Adding email/password or social OAuth authentication
- Setting up 2FA, passkeys, magic links, advanced auth features
- Building multi-tenant apps with organization support
- Managing sessions and user lifecycle
- Working with any framework (Next.js, Nuxt, SvelteKit, Remix, Astro, Hono, Express, etc.)
Quick Start
Installation
npm install better-auth
# or pnpm/yarn/bun add better-auth
Environment Setup
Create .env:
BETTER_AUTH_SECRET=<generated-secret-32-chars-min>
BETTER_AUTH_URL=http://localhost:3000
Basic Server Setup
Create auth.ts (root, lib/, utils/, or under src/app/server/):
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: {
// See references/database-integration.md
},
emailAndPassword: {
enabled: true,
autoSignIn: true
},
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}
}
});
Database Schema
npx @better-auth/cli generate # Generate schema/migrations
npx @better-auth/cli migrate # Apply migrations (Kysely only)
Mount API Handler
Next.js App Router:
// app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { POST, GET } = toNextJsHandler(auth);
Other frameworks: See references/email-password-auth.md#framework-setup
Client Setup
Create auth-client.ts:
import { createAuthClient } from "better-auth/client";
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_BETTER_AUTH_URL || "http://localhost:3000"
});
Basic Usage
// Sign up
await authClient.signUp.email({
email: "user@example.com",
password: "secure123",
name: "John Doe"
});
// Sign in
await authClient.signIn.email({
email: "user@example.com",
password: "secure123"
});
// OAuth
await authClient.signIn.social({ provider: "github" });
// Session
const { data: session } = authClient.useSession(); // React/Vue/Svelte
const { data: session } = await authClient.getSession(); // Vanilla JS
Feature Selection Matrix
| Feature | Plugin Required | Use Case | Reference |
|---|---|---|---|
| Email/Password | No (built-in) | Basic auth | email-password-auth.md |
| OAuth (GitHub, Google, etc.) | No (built-in) | Social login | oauth-providers.md |
| Email Verification | No (built-in) | Verify email addresses | email-password-auth.md |
| Password Reset | No (built-in) | Forgot password flow | email-password-auth.md |
| Two-Factor Auth (2FA/TOTP) | Yes (twoFactor) |
Enhanced security | advanced-features.md |
| Passkeys/WebAuthn | Yes (passkey) |
Passwordless auth | advanced-features.md |
| Magic Link | Yes (magicLink) |
Email-based login | advanced-features.md |
| Username Auth | Yes (username) |
Username login | email-password-auth.md |
| Organizations/Multi-tenant | Yes (organization) |
Team/org features | advanced-features.md |
| Rate Limiting | No (built-in) | Prevent abuse | advanced-features.md |
| Session Management | No (built-in) | User sessions | advanced-features.md |
Auth Method Selection Guide
Choose Email/Password when:
- Building standard web app with traditional auth
- Need full control over user credentials
- Targeting users who prefer email-based accounts
Choose OAuth when:
- Want quick signup with minimal friction
- Users already have social accounts
- Need access to social profile data
Choose Passkeys when:
- Want passwordless experience
- Targeting modern browsers/devices
- Security is top priority
Choose Magic Link when:
- Want passwordless without WebAuthn complexity
- Targeting email-first users
- Need temporary access links
Combine Multiple Methods when:
- Want flexibility for different user preferences
- Building enterprise apps with various auth requirements
- Need progressive enhancement (start simple, add more options)
Core Architecture
Better Auth uses client-server architecture:
- Server (
better-auth): Handles auth logic, database ops, API routes - Client (
better-auth/client): Provides hooks/methods for frontend - Plugins: Extend both server/client functionality
Implementation Checklist
- [ ] Install
better-authpackage - [ ] Set environment variables (SECRET, URL)
- [ ] Create auth server instance with database config
- [ ] Run schema migration (
npx @better-auth/cli generate) - [ ] Mount API handler in framework
- [ ] Create client instance
- [ ] Implement sign-up/sign-in UI
- [ ] Add session management to components
- [ ] Set up protected routes/middleware
- [ ] Add plugins as needed (regenerate schema after)
- [ ] Test complete auth flow
- [ ] Configure email sending (verification/reset)
- [ ] Enable rate limiting for production
- [ ] Set up error handling
Reference Documentation
Core Authentication
- Email/Password Authentication - Email/password setup, verification, password reset, username auth
- OAuth Providers - Social login setup, provider configuration, token management
- Database Integration - Database adapters, schema setup, migrations
Advanced Features
- Advanced Features - 2FA/MFA, passkeys, magic links, organizations, rate limiting, session management
Scripts
scripts/better_auth_init.py- Initialize Better Auth configuration with interactive setup
Resources
04 同仓库更多 Skills
Next.js 全栈 Web 开发
web-frameworks
使用 Next.js(App Router、Server Components、RSC、PPR、SSR、SSG、ISR)、Turborepo(monorepo 管理、任务流水线、远程缓存、并行执行)和 RemixIcon(3100+ 个线性/填充风格 SVG 图标)构建现代全栈 Web 应用。适用于创建 React 应用、实现服务端渲染、搭建包含多个包的 monorepo、优化构建性能与缓存策略、添加图标库、管理共享依赖,或开发 TypeScript 全栈项目。
UI 界面样式设计与实现
ui-styling
使用 shadcn/ui 组件(基于 Radix UI + Tailwind 构建)、Tailwind CSS 工具类优先(utility-first)的样式方案以及基于画布的视觉设计,创建美观且无障碍的用户界面。适用于构建用户界面、实现设计系统、创建响应式布局、添加无障碍组件(对话框、下拉菜单、表单、表格)、定制主题与配色、实现深色模式、生成视觉设计与海报,或在多个应用间建立一致的样式规范。
Three.js 三维网页应用开发
threejs
使用 Three.js(WebGL/WebGPU)构建 3D Web 应用。适用于 3D 场景、动画、自定义着色器、PBR 材质、VR/XR 体验、游戏、数据可视化和产品配置器。
结构化逐步推理
sequential-thinking
当复杂问题需要系统的逐步推理,并能够修正思路、分支到备选方案或动态调整范围时使用。适用于多阶段分析、设计规划、问题分解或初始范围尚不清晰的任务。
技术方案研究规划
research
当需要对可扩展、安全且可维护的技术方案进行研究、分析和规划时使用。
技术方案规划
planning
适用于需要规划可扩展、安全且可维护的技术方案时。