better-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

better-auth

Better Auth

Status: Production Ready Last Updated: 2025-12-26 Package:
better-auth@1.4.9
(ESM-only) Dependencies: Drizzle ORM or Kysely (required for D1)

状态:已就绪可用于生产环境 最后更新时间:2025-12-26 包版本
better-auth@1.4.9
(仅支持ESM) 依赖项:Drizzle ORM 或 Kysely(D1环境下必填)

Quick Start (5 Minutes)

快速开始(5分钟完成)

Installation

安装

Option 1: Drizzle ORM (Recommended)
bash
bun add better-auth drizzle-orm drizzle-kit
Option 2: Kysely
bash
bun add better-auth kysely @noxharmonium/kysely-d1
选项1:Drizzle ORM(推荐)
bash
bun add better-auth drizzle-orm drizzle-kit
选项2:Kysely
bash
bun add better-auth kysely @noxharmonium/kysely-d1

⚠️ v1.4.0+ Requirements

⚠️ v1.4.0+ 版本要求

better-auth v1.4.0+ is ESM-only. Ensure:
package.json:
json
{
  "type": "module"
}
Upgrading from v1.3.x? Load
references/migration-guide-1.4.0.md
better-auth v1.4.0+ 仅支持ESM。请确保:
package.json配置:
json
{
  "type": "module"
}
从v1.3.x升级? 请查看
references/migration-guide-1.4.0.md

⚠️ CRITICAL: D1 Adapter Requirements

⚠️ 关键:D1适配器要求

better-auth DOES NOT have a direct
d1Adapter()
. You MUST use either:
  1. Drizzle ORM (recommended) -
    drizzleAdapter()
  2. Kysely (alternative) - Kysely instance with D1Dialect
typescript
// ❌ WRONG - This doesn't exist
import { d1Adapter } from 'better-auth/adapters/d1'

// ✅ CORRECT - Use Drizzle
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { drizzle } from 'drizzle-orm/d1'
better-auth 没有直接的
d1Adapter()
方法。你必须使用以下二者之一:
  1. Drizzle ORM(推荐)-
    drizzleAdapter()
  2. Kysely(替代方案)- 搭配D1Dialect的Kysely实例
typescript
// ❌ 错误用法 - 该方法不存在
import { d1Adapter } from 'better-auth/adapters/d1'

// ✅ 正确用法 - 使用Drizzle
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { drizzle } from 'drizzle-orm/d1'

Minimal Setup (Cloudflare Workers + Drizzle)

最小化配置(Cloudflare Workers + Drizzle)

1. Create D1 Database:
bash
wrangler d1 create my-app-db
2. Define Schema (
src/db/schema.ts
):
typescript
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";

export const user = sqliteTable("user", {
  id: text().primaryKey(),
  name: text().notNull(),
  email: text().notNull().unique(),
  emailVerified: integer({ mode: "boolean" }).notNull().default(false),
  image: text(),
});

export const session = sqliteTable("session", {
  id: text().primaryKey(),
  userId: text().notNull().references(() => user.id, { onDelete: "cascade" }),
  token: text().notNull(),
  expiresAt: integer({ mode: "timestamp" }).notNull(),
});

// See references/database-schema.ts for complete schema
3. Initialize Auth (
src/auth.ts
):
typescript
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./db/schema";

export function createAuth(env: { DB: D1Database; BETTER_AUTH_SECRET: string }) {
  const db = drizzle(env.DB, { schema });

  return betterAuth({
    baseURL: env.BETTER_AUTH_URL,
    secret: env.BETTER_AUTH_SECRET,
    database: drizzleAdapter(db, { provider: "sqlite" }),
    emailAndPassword: { enabled: true },
  });
}
4. Create Worker (
src/index.ts
):
typescript
import { Hono } from "hono";
import { createAuth } from "./auth";

const app = new Hono<{ Bindings: Env }>();

app.all("/api/auth/*", async (c) => {
  const auth = createAuth(c.env);
  return auth.handler(c.req.raw);
});

export default app;
5. Deploy:
bash
bunx drizzle-kit generate
wrangler d1 migrations apply my-app-db --remote
wrangler deploy

1. 创建D1数据库:
bash
wrangler d1 create my-app-db
2. 定义数据库Schema
src/db/schema.ts
):
typescript
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";

export const user = sqliteTable("user", {
  id: text().primaryKey(),
  name: text().notNull(),
  email: text().notNull().unique(),
  emailVerified: integer({ mode: "boolean" }).notNull().default(false),
  image: text(),
});

export const session = sqliteTable("session", {
  id: text().primaryKey(),
  userId: text().notNull().references(() => user.id, { onDelete: "cascade" }),
  token: text().notNull(),
  expiresAt: integer({ mode: "timestamp" }).notNull(),
});

// 完整Schema请查看references/database-schema.ts
3. 初始化认证服务
src/auth.ts
):
typescript
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { drizzle } from "drizzle-orm/d1";
import * as schema from "./db/schema";

export function createAuth(env: { DB: D1Database; BETTER_AUTH_SECRET: string }) {
  const db = drizzle(env.DB, { schema });

  return betterAuth({
    baseURL: env.BETTER_AUTH_URL,
    secret: env.BETTER_AUTH_SECRET,
    database: drizzleAdapter(db, { provider: "sqlite" }),
    emailAndPassword: { enabled: true },
  });
}
4. 创建Worker服务
src/index.ts
):
typescript
import { Hono } from "hono";
import { createAuth } from "./auth";

const app = new Hono<{ Bindings: Env }>();

app.all("/api/auth/*", async (c) => {
  const auth = createAuth(c.env);
  return auth.handler(c.req.raw);
});

export default app;
5. 部署:
bash
bunx drizzle-kit generate
wrangler d1 migrations apply my-app-db --remote
wrangler deploy

Decision Tree

决策树

For code examples and syntax, always consult better-auth.com/docs.
Is this a new/empty project?
├─ YES → New project setup
│   1. Identify framework (Next.js, Nuxt, Workers, etc.)
│   2. Choose database (D1, PostgreSQL, MongoDB, MySQL)
│   3. Install better-auth + Drizzle/Kysely
│   4. Create auth.ts + auth-client.ts
│   5. Set up route handler (see Quick Start above)
│   6. Run migrations (Drizzle Kit for D1)
│   7. Add features via plugins (2FA, organizations, etc.)
└─ NO → Does project have existing auth?
    ├─ YES → Migration/enhancement
    │   • Audit current auth for gaps
    │   • Plan incremental migration
    │   • See references/framework-comparison.md for migration guides
    └─ NO → Add auth to existing project
        1. Analyze project structure
        2. Install better-auth + adapter
        3. Create auth config (see Quick Start)
        4. Add route handler to existing routes
        5. Run schema migrations
        6. Integrate into existing pages/components

代码示例和语法相关问题,请始终参考better-auth.com/docs
是否为新项目/空项目?
├─ 是 → 新项目初始化
│   1. 确定使用的框架(Next.js、Nuxt、Workers等)
│   2. 选择数据库(D1、PostgreSQL、MongoDB、MySQL)
│   3. 安装better-auth + Drizzle/Kysely
│   4. 创建auth.ts + auth-client.ts
│   5. 配置路由处理器(参考上方快速开始步骤)
│   6. 执行数据库迁移(D1使用Drizzle Kit)
│   7. 通过插件添加功能(2FA、组织管理等)
└─ 否 → 项目已有认证系统?
    ├─ 是 → 迁移/增强现有系统
    │   • 审计当前认证系统的不足
    │   • 规划增量迁移方案
    │   • 查看references/framework-comparison.md获取迁移指南
    └─ 否 → 为现有项目添加认证
        1. 分析项目结构
        2. 安装better-auth + 对应适配器
        3. 创建认证配置(参考快速开始)
        4. 在现有路由中添加认证路由处理器
        5. 执行Schema迁移
        6. 集成到现有页面/组件中

Critical Rules

关键规则

MUST DO

必须执行

✅ Use Drizzle/Kysely adapter (d1Adapter doesn't exist) ✅ Use Drizzle Kit for migrations (not
better-auth migrate
) ✅ Set BETTER_AUTH_SECRET via
wrangler secret put
✅ Configure CORS with
credentials: true
✅ Match OAuth callback URLs exactly (no trailing slash) ✅ Apply migrations to local D1 before
wrangler dev
✅ Use camelCase column names in schema
✅ 使用Drizzle/Kysely适配器(d1Adapter不存在) ✅ 使用Drizzle Kit执行迁移(不要用
better-auth migrate
) ✅ 通过
wrangler secret put
设置BETTER_AUTH_SECRET ✅ 配置CORS时设置
credentials: true
✅ OAuth回调URL必须完全匹配(不能有末尾斜杠) ✅ 在
wrangler dev
前先在本地D1上执行迁移 ✅ Schema中使用小驼峰(camelCase)命名列

NEVER DO

禁止操作

❌ Use
d1Adapter
or
better-auth migrate
with D1 ❌ Forget CORS credentials or mismatch OAuth URLs ❌ Use snake_case columns without CamelCasePlugin ❌ Skip local migrations or hardcode secrets ❌ Leave sendVerificationEmail unimplemented
❌ 在D1环境中使用
d1Adapter
better-auth migrate
❌ 忘记配置CORS credentials或OAuth URL不匹配 ❌ 在未添加CamelCasePlugin的情况下使用蛇形命名(snake_case)列 ❌ 跳过本地迁移或硬编码密钥 ❌ 未实现sendVerificationEmail功能

⚠️ v1.4.0+ Breaking Changes

⚠️ v1.4.0+ 破坏性变更

ESM-only (no CommonJS):
json
// package.json required
{ "type": "module" }
API Renames:
  • forgetPassword
    requestPasswordReset
  • POST
    /account-info
    → GET
    /account-info
Callback Signatures:
typescript
// v1.3.x: request parameter
sendVerificationEmail: async ({ user, url, request }) => {}

// v1.4.0+: ctx parameter
sendVerificationEmail: async ({ user, url, ctx }) => {}
Load
references/migration-guide-1.4.0.md
when upgrading from <1.4.0
仅支持ESM(不支持CommonJS):
json
// 必须在package.json中配置
{ "type": "module" }
API重命名:
  • forgetPassword
    requestPasswordReset
  • POST
    /account-info
    → GET
    /account-info
回调函数签名变更:
typescript
// v1.3.x: 接收request参数
sendVerificationEmail: async ({ user, url, request }) => {}

// v1.4.0+: 接收ctx参数
sendVerificationEmail: async ({ user, url, ctx }) => {}
从v1.3.x升级到v1.4.0+请查看
references/migration-guide-1.4.0.md

New in v1.4.4-1.4.8

v1.4.4-1.4.8版本新增功能

Key additions since v1.4.3:
  • Background Tasks (v1.4.8): Global
    backgroundTasks
    config to defer email sending
  • New OAuth Providers: Patreon (v1.4.8), Vercel (v1.4.3), Kick (v1.4.6) with refresh tokens
  • OAuth 2.1 Plugin (v1.4.8): Standards-compliant OAuth implementation
  • CLI Tool (v1.4.4):
    better-auth
    CLI with project scaffolding
  • SAML/SSO: Clock skew validation (v1.4.7), InResponseTo, OIDC discovery
  • Admin Permissions (v1.4.7): Admin role with granular user update permissions
  • ctx.isTrustedDomain (v1.4.6): Helper for domain verification
Load
references/v1.4-features.md
for detailed implementation guides.

v1.4.3之后的关键更新:
  • 后台任务(v1.4.8):全局
    backgroundTasks
    配置,用于延迟发送邮件
  • 新增OAuth提供商:Patreon(v1.4.8)、Vercel(v1.4.3)、Kick(v1.4.6),均支持刷新令牌
  • OAuth 2.1插件(v1.4.8):符合标准的OAuth实现
  • CLI工具(v1.4.4):
    better-auth
    CLI,支持项目脚手架
  • SAML/SSO:时钟偏移验证(v1.4.7)、InResponseTo、OIDC发现
  • 管理员权限(v1.4.7):管理员角色,支持细粒度的用户更新权限
  • ctx.isTrustedDomain(v1.4.6):域名验证辅助工具
详细实现指南请查看
references/v1.4-features.md

Quick Reference

快速参考

Environment Variables

环境变量

VariablePurposeExample
BETTER_AUTH_SECRET
Encryption secret (min 32 chars)Generate:
openssl rand -base64 32
BETTER_AUTH_URL
Base URL
https://example.com
or
http://localhost:8787
DATABASE_URL
Database connection (optional for D1)PostgreSQL/MySQL connection string
Note: Only define
baseURL
/
secret
in config if env vars are NOT set.
变量名用途示例
BETTER_AUTH_SECRET
加密密钥(至少32个字符)生成方式:
openssl rand -base64 32
BETTER_AUTH_URL
基础URL
https://example.com
http://localhost:8787
DATABASE_URL
数据库连接字符串(D1环境可选)PostgreSQL/MySQL连接字符串
注意:如果已设置环境变量,则无需在配置中重复定义
baseURL
/
secret

CLI Commands

CLI命令

CommandPurpose
npx @better-auth/cli@latest migrate
Apply schema (built-in Kysely adapter only)
npx @better-auth/cli@latest generate
Generate schema for Prisma/Drizzle
bunx drizzle-kit generate
D1: Use this to generate Drizzle migrations
wrangler d1 migrations apply DB_NAME
D1: Use this to apply migrations
Re-run after adding/changing plugins.
命令用途
npx @better-auth/cli@latest migrate
应用Schema变更(仅内置Kysely适配器支持)
npx @better-auth/cli@latest generate
为Prisma/Drizzle生成Schema
bunx drizzle-kit generate
D1环境请使用该命令生成Drizzle迁移文件
wrangler d1 migrations apply DB_NAME
D1环境请使用该命令执行迁移
添加或修改插件后请重新执行上述命令。

Core Config Options

核心配置选项

OptionNotes
appName
Optional display name
baseURL
Only if
BETTER_AUTH_URL
not set
basePath
Default
/api/auth
. Set
/
for root.
secret
Only if
BETTER_AUTH_SECRET
not set (min 32 chars)
database
Required for most features. Use
drizzleAdapter()
or Kysely for D1
secondaryStorage
Redis/KV for sessions & rate limits
emailAndPassword
{ enabled: true }
to activate
socialProviders
{ google: { clientId, clientSecret }, ... }
plugins
Array of plugins (import from dedicated paths)
trustedOrigins
CSRF whitelist for cross-origin requests
选项说明
appName
可选的应用显示名称
baseURL
未设置
BETTER_AUTH_URL
环境变量时必填
basePath
默认值
/api/auth
,可设置为
/
表示根路径
secret
未设置
BETTER_AUTH_SECRET
环境变量时必填(至少32个字符)
database
大多数功能必填。D1环境使用
drizzleAdapter()
或Kysely
secondaryStorage
用于存储会话和限流数据的Redis/KV
emailAndPassword
设置
{ enabled: true }
以启用邮箱密码认证
socialProviders
配置
{ google: { clientId, clientSecret }, ... }
启用社交登录
plugins
插件数组(需从专用路径导入)
trustedOrigins
跨域请求的CSRF白名单

Common Plugins

常用插件

Import from dedicated paths for tree-shaking:
typescript
import { twoFactor } from "better-auth/plugins/two-factor"
import { organization } from "better-auth/plugins/organization"
import { passkey } from "@better-auth/passkey"  // Separate package
NOT
from "better-auth/plugins"
.

请从专用路径导入以支持摇树优化:
typescript
import { twoFactor } from "better-auth/plugins/two-factor"
import { organization } from "better-auth/plugins/organization"
import { passkey } from "@better-auth/passkey"  // 独立包
不要
"better-auth/plugins"
导入。

Top 5 Errors (See references/error-catalog.md for all 15)

Top 5常见错误(全部15种错误请查看references/error-catalog.md)

Error #1: "d1Adapter is not exported"

错误1:"d1Adapter is not exported"

Problem: Trying to use non-existent
d1Adapter
Solution: Use
drizzleAdapter
or Kysely instead (see Quick Start above)
问题:尝试使用不存在的
d1Adapter
方法 解决方案:改用
drizzleAdapter
或Kysely(参考上方快速开始部分)

Error #2: Schema Generation Fails

错误2:Schema生成失败

Problem:
better-auth migrate
doesn't work with D1 Solution: Use
bunx drizzle-kit generate
then
wrangler d1 migrations apply
问题
better-auth migrate
在D1环境中无法工作 解决方案:使用
bunx drizzle-kit generate
生成迁移文件,再执行
wrangler d1 migrations apply

Error #3: CamelCase vs snake_case Mismatch

错误3:驼峰命名与蛇形命名不匹配

Problem: Database uses
email_verified
but better-auth expects
emailVerified
Solution: Use camelCase in schema or add
CamelCasePlugin
to Kysely
问题:数据库使用
email_verified
,但better-auth期望
emailVerified
解决方案:Schema中使用小驼峰命名,或为Kysely添加
CamelCasePlugin

Error #4: CORS Errors

错误4:CORS错误

Problem:
Access-Control-Allow-Origin
errors, cookies not sent Solution: Configure CORS with
credentials: true
and correct origins
问题:出现
Access-Control-Allow-Origin
错误,Cookie无法发送 解决方案:配置CORS时设置
credentials: true
并指定正确的源

Error #5: OAuth Redirect URI Mismatch

错误5:OAuth重定向URI不匹配

Problem: Social sign-in fails with "redirect_uri_mismatch" Solution: Ensure exact match:
https://yourdomain.com/api/auth/callback/google
Load
references/error-catalog.md
for all 15 errors with detailed solutions.

问题:社交登录失败,提示"redirect_uri_mismatch" 解决方案:确保回调URL完全匹配,例如:
https://yourdomain.com/api/auth/callback/google
全部15种错误及详细解决方案请查看
references/error-catalog.md

Common Use Cases

常见使用场景

Use Case 1: Email/Password Authentication

场景1:邮箱/密码认证

When: Basic authentication without social providers Quick Pattern:
typescript
// Client
await authClient.signIn.email({
  email: "user@example.com",
  password: "password123",
});

// Server - enable in config
emailAndPassword: {
  enabled: true,
  requireEmailVerification: true,
}
Load:
references/setup-guide.md
→ Step 5
适用情况:无需社交登录的基础认证场景 快速实现代码:
typescript
// 客户端
await authClient.signIn.email({
  email: "user@example.com",
  password: "password123",
});

// 服务端 - 在配置中启用
emailAndPassword: {
  enabled: true,
  requireEmailVerification: true,
}
详细指南:查看
references/setup-guide.md
→ 步骤5

Use Case 2: Social Authentication (45+ Providers)

场景2:社交认证(支持45+种提供商)

When: Allow users to sign in with social accounts Supported: Google, GitHub, Microsoft, Apple, Discord, TikTok, Twitch, Spotify, LinkedIn, Slack, Reddit, Facebook, Twitter/X, Patreon, Vercel, Kick, and 30+ more. Quick Pattern:
typescript
// Client
await authClient.signIn.social({
  provider: "google",
  callbackURL: "/dashboard",
});

// Server config
socialProviders: {
  google: {
    clientId: env.GOOGLE_CLIENT_ID,
    clientSecret: env.GOOGLE_CLIENT_SECRET,
    scope: ["openid", "email", "profile"],
  },
}
Load:
references/setup-guide.md
→ Step 5
适用情况:允许用户通过社交账号登录 支持的提供商:Google、GitHub、Microsoft、Apple、Discord、TikTok、Twitch、Spotify、LinkedIn、Slack、Reddit、Facebook、Twitter/X、Patreon、Vercel、Kick等30余种。 快速实现代码:
typescript
// 客户端
await authClient.signIn.social({
  provider: "google",
  callbackURL: "/dashboard",
});

// 服务端配置
socialProviders: {
  google: {
    clientId: env.GOOGLE_CLIENT_ID,
    clientSecret: env.GOOGLE_CLIENT_SECRET,
    scope: ["openid", "email", "profile"],
  },
}
详细指南:查看
references/setup-guide.md
→ 步骤5

Use Case 3: Protected API Routes

场景3:受保护的API路由

When: Need to verify user is authenticated Quick Pattern:
typescript
app.get("/api/protected", async (c) => {
  const auth = createAuth(c.env);
  const session = await auth.api.getSession({
    headers: c.req.raw.headers,
  });

  if (!session) {
    return c.json({ error: "Unauthorized" }, 401);
  }

  return c.json({ data: "protected", user: session.user });
});
Load:
references/cloudflare-worker-drizzle.ts
适用情况:需要验证用户是否已认证 快速实现代码:
typescript
app.get("/api/protected", async (c) => {
  const auth = createAuth(c.env);
  const session = await auth.api.getSession({
    headers: c.req.raw.headers,
  });

  if (!session) {
    return c.json({ error: "Unauthorized" }, 401);
  }

  return c.json({ data: "protected", user: session.user });
});
详细示例:查看
references/cloudflare-worker-drizzle.ts

Use Case 4: Multi-Tenant with Organizations

场景4:多租户组织管理

When: Building SaaS with teams/organizations Load:
references/advanced-features.md
→ Organizations & Teams
适用情况:构建支持团队/组织的SaaS应用 详细指南:查看
references/advanced-features.md
→ 组织与团队管理

Use Case 5: Two-Factor Authentication

场景5:双因素认证(2FA)

When: Need extra security with 2FA/TOTP Load:
references/advanced-features.md
→ Two-Factor Authentication

适用情况:需要额外安全保障的场景 详细指南:查看
references/advanced-features.md
→ 双因素认证

When to Load References

何时参考对应文档

Load
references/setup-guide.md
when
:
  • User needs complete 8-step setup walkthrough
  • User asks about Kysely adapter alternative
  • User needs help with migrations or deployment
  • User asks about wrangler.toml configuration
Load
references/error-catalog.md
when
:
  • Encountering any of the 12 documented errors
  • User reports D1 adapter, schema, CORS, or OAuth issues
  • User asks about troubleshooting or debugging
  • User needs prevention checklist
Load
references/advanced-features.md
when
:
  • User asks about 2FA, passkeys, or magic links
  • User needs organizations, teams, or RBAC
  • User asks about rate limiting or session management
  • User wants migration guide from Clerk or Auth.js
  • User needs security best practices or performance optimization
Load
references/cloudflare-worker-drizzle.ts
when
:
  • User needs complete Worker implementation example
  • User asks for production-ready code
  • User wants to see full auth flow with protected routes
Load
references/cloudflare-worker-kysely.ts
when
:
  • User prefers Kysely over Drizzle
  • User asks for Kysely-specific implementation
Load
references/database-schema.ts
when
:
  • User needs complete better-auth schema with all tables
  • User asks about custom tables or schema extension
  • User needs TypeScript types for database
Load
references/react-client-hooks.tsx
when
:
  • User building React/Next.js frontend
  • User needs login forms, session hooks, or protected routes
  • User asks about client-side implementation
Load
references/configuration-guide.md
when
:
  • User asks about production configuration
  • User needs environment variable setup or wrangler.toml
  • User asks about session configuration or ESM setup
  • User needs CORS configuration, rate limiting, or API keys
  • User asks about troubleshooting configuration issues
Load
references/framework-comparison.md
when
:
  • User asks "better-auth vs Clerk" or "vs Auth.js"
  • User needs help choosing auth framework
  • User wants feature comparison, migration advice, or cost analysis
  • User asks about v1.4.0+ new features (database joins, stateless sessions)
Load
references/migration-guide-1.4.0.md
when
:
  • User upgrading from better-auth <1.4.0 to 1.4.0+
  • User encounters
    forgetPassword
    errors or ESM issues
  • User asks about breaking changes or migration steps
  • User needs to migrate callback functions or API endpoints
Load
references/v1.4-features.md
when
:
  • User asks about background tasks or deferred email sending
  • User needs Patreon, Vercel, or Kick OAuth provider setup
  • User asks about OAuth 2.1 compliance
  • User needs SAML/SSO with clock skew or OIDC discovery
  • User asks about the better-auth CLI tool
  • User needs admin role permissions configuration
  • User asks about ctx.isTrustedDomain or domain verification
Load
references/nextjs/README.md
when
:
  • User building Next.js app with PostgreSQL (not Cloudflare D1)
  • User needs organizations and 2FA example
  • User asks about Next.js-specific implementation
Load
references/nextjs/postgres-example.ts
when
:
  • User needs complete Next.js API route implementation
  • User wants to see organizations + 2FA in practice
  • User asks for PostgreSQL setup with Drizzle
查看
references/setup-guide.md
的场景
:
  • 需要完整的8步安装指南
  • 咨询Kysely适配器的替代方案
  • 需要迁移或部署相关帮助
  • 咨询wrangler.toml配置
查看
references/error-catalog.md
的场景
:
  • 遇到任何已记录的12种错误
  • 用户反馈D1适配器、Schema、CORS或OAuth相关问题
  • 咨询故障排查或调试方法
  • 需要错误预防清单
查看
references/advanced-features.md
的场景
:
  • 咨询2FA、Passkey或魔法链接
  • 需要组织、团队或RBAC功能
  • 咨询限流或会话管理
  • 需要从Clerk或Auth.js迁移的指南
  • 需要安全最佳实践或性能优化建议
查看
references/cloudflare-worker-drizzle.ts
的场景
:
  • 需要完整的Worker实现示例
  • 咨询生产就绪代码
  • 查看包含受保护路由的完整认证流程
查看
references/cloudflare-worker-kysely.ts
的场景
:
  • 偏好使用Kysely而非Drizzle
  • 咨询Kysely专属实现方案
查看
references/database-schema.ts
的场景
:
  • 需要完整的better-auth Schema及所有表结构
  • 咨询自定义表或Schema扩展
  • 需要数据库的TypeScript类型定义
查看
references/react-client-hooks.tsx
的场景
:
  • 构建React/Next.js前端
  • 需要登录表单、会话钩子或受保护路由
  • 咨询客户端实现方案
查看
references/configuration-guide.md
的场景
:
  • 咨询生产环境配置
  • 需要环境变量或wrangler.toml设置
  • 咨询会话配置或ESM设置
  • 需要CORS配置、限流或API密钥相关内容
  • 咨询配置相关的故障排查
查看
references/framework-comparison.md
的场景
:
  • 咨询"better-auth vs Clerk"或"vs Auth.js"
  • 需要选择认证框架的建议
  • 需要功能对比、迁移建议或成本分析
  • 咨询v1.4.0+新增功能(数据库关联、无状态会话)
查看
references/migration-guide-1.4.0.md
的场景
:
  • 从better-auth <1.4.0升级到1.4.0+
  • 遇到
    forgetPassword
    错误或ESM相关问题
  • 咨询破坏性变更或迁移步骤
  • 需要迁移回调函数或API端点
查看
references/v1.4-features.md
的场景
:
  • 咨询后台任务或延迟邮件发送
  • 需要Patreon、Vercel或Kick OAuth提供商配置
  • 咨询OAuth 2.1合规性
  • 需要SAML/SSO的时钟偏移或OIDC发现配置
  • 咨询better-auth CLI工具
  • 需要管理员角色权限配置
  • 咨询ctx.isTrustedDomain或域名验证
查看
references/nextjs/README.md
的场景
:
  • 构建使用PostgreSQL的Next.js应用(非Cloudflare D1)
  • 需要组织和2FA示例
  • 咨询Next.js专属实现方案
查看
references/nextjs/postgres-example.ts
的场景
:
  • 需要完整的Next.js API路由实现
  • 查看组织+2FA的实际代码示例
  • 需要PostgreSQL与Drizzle的配置指南

Framework-Specific Setup

框架专属配置指南

Load
references/frameworks/nextjs.md
when
:
  • User building with Next.js (App Router or Pages Router)
  • User needs middleware, Server Components, or API routes
Load
references/frameworks/nuxt.md
when
:
  • User building with Nuxt 3
  • User needs H3 handlers, composables, or server routes
Load
references/frameworks/remix.md
when
:
  • User building with Remix
  • User needs loader/action patterns or session handling
Load
references/frameworks/sveltekit.md
when
:
  • User building with SvelteKit
  • User needs hooks, load functions, or stores
Load
references/frameworks/api-frameworks.md
when
:
  • User building with Express, Fastify, NestJS, or Hono (non-Cloudflare)
  • User needs middleware or route configuration
Load
references/frameworks/expo-mobile.md
when
:
  • User building React Native or Expo app
  • User needs SecureStore, deep linking, or mobile auth
查看
references/frameworks/nextjs.md
的场景
:
  • 使用Next.js(App Router或Pages Router)
  • 需要中间件、服务端组件或API路由相关配置
查看
references/frameworks/nuxt.md
的场景
:
  • 使用Nuxt 3
  • 需要H3处理器、组合式函数或服务端路由相关配置
查看
references/frameworks/remix.md
的场景
:
  • 使用Remix
  • 需要loader/action模式或会话处理相关配置
查看
references/frameworks/sveltekit.md
的场景
:
  • 使用SvelteKit
  • 需要钩子、加载函数或状态存储相关配置
查看
references/frameworks/api-frameworks.md
的场景
:
  • 使用Express、Fastify、NestJS或Hono(非Cloudflare环境)
  • 需要中间件或路由配置
查看
references/frameworks/expo-mobile.md
的场景
:
  • 构建React Native或Expo应用
  • 需要SecureStore、深度链接或移动端认证相关配置

Database Adapters

数据库适配器指南

Load
references/databases/postgresql.md
when
:
  • User using PostgreSQL with Drizzle or Prisma
  • User needs Neon, Supabase, or connection pooling setup
Load
references/databases/mongodb.md
when
:
  • User using MongoDB
  • User needs Atlas setup or indexes
Load
references/databases/mysql.md
when
:
  • User using MySQL or PlanetScale
  • User needs Vitess compatibility guidance
查看
references/databases/postgresql.md
的场景
:
  • 使用PostgreSQL搭配Drizzle或Prisma
  • 需要Neon、Supabase或连接池配置
查看
references/databases/mongodb.md
的场景
:
  • 使用MongoDB
  • 需要Atlas配置或索引优化
查看
references/databases/mysql.md
的场景
:
  • 使用MySQL或PlanetScale
  • 需要Vitess兼容性指导

Plugin Guides

插件指南

Load
references/plugins/authentication.md
when
:
  • User needs 2FA, passkeys, magic links, email OTP, or anonymous users
  • User asks about enhanced authentication methods
Load
references/plugins/enterprise.md
when
:
  • User needs organizations, SSO/SAML, SCIM, or admin dashboard
  • User building multi-tenant or enterprise application
Load
references/plugins/api-tokens.md
when
:
  • User needs API keys, bearer tokens, JWT, or OIDC provider
  • User building API authentication for third parties
Load
references/plugins/payments.md
when
:
  • User needs Stripe or Polar integration
  • User building subscription or payment features

查看
references/plugins/authentication.md
的场景
:
  • 需要2FA、Passkey、魔法链接、邮箱OTP或匿名用户功能
  • 咨询增强型认证方法
查看
references/plugins/enterprise.md
的场景
:
  • 需要组织、SSO/SAML、SCIM或管理员控制台
  • 构建多租户或企业级应用
查看
references/plugins/api-tokens.md
的场景
:
  • 需要API密钥、Bearer令牌、JWT或OIDC提供商
  • 构建面向第三方的API认证
查看
references/plugins/payments.md
的场景
:
  • 需要Stripe或Polar集成
  • 构建订阅或支付功能

Configuration Reference

配置参考

Quick Config (ESM-only in v1.4.0+):
typescript
export const auth = betterAuth({
  baseURL: env.BETTER_AUTH_URL,
  secret: env.BETTER_AUTH_SECRET,
  database: drizzleAdapter(db, { provider: "sqlite" }),
});
Load
references/configuration-guide.md
for
:
  • Production configuration with email/password and social providers
  • wrangler.toml setup and environment variables
  • Session configuration, CORS setup, and ESM requirements
  • Rate limiting, API keys (v1.4.0+), and troubleshooting

快速配置(v1.4.0+仅支持ESM):
typescript
export const auth = betterAuth({
  baseURL: env.BETTER_AUTH_URL,
  secret: env.BETTER_AUTH_SECRET,
  database: drizzleAdapter(db, { provider: "sqlite" }),
});
查看
references/configuration-guide.md
获取以下内容
:
  • 包含邮箱密码和社交登录的生产环境配置
  • wrangler.toml设置和环境变量配置
  • 会话配置、CORS设置及ESM要求
  • 限流、API密钥(v1.4.0+)及故障排查

Using Bundled Resources

使用捆绑资源

References (references/)

参考文档(references/)

  • setup-guide.md - Complete 8-step setup (D1 → Drizzle → Deploy)
  • error-catalog.md - All 12 errors with solutions and prevention checklist
  • advanced-features.md - 2FA, organizations, rate limiting, passkeys, magic links, migrations
  • configuration-guide.md - Production config, environment variables, CORS, rate limiting
  • framework-comparison.md - better-auth vs Clerk vs Auth.js, migration paths, TCO
  • migration-guide-1.4.0.md - Upgrading from v1.3.x to v1.4.0+ (ESM, API changes)
  • cloudflare-worker-drizzle.ts - Complete Worker with Drizzle auth
  • cloudflare-worker-kysely.ts - Complete Worker with Kysely auth
  • database-schema.ts - Complete better-auth Drizzle schema
  • react-client-hooks.tsx - React components with auth hooks
  • v1.4-features.md - Background tasks, new OAuth providers, SAML/SSO, CLI
  • setup-guide.md - 完整的8步安装指南(D1 → Drizzle → 部署)
  • error-catalog.md - 所有12种错误及解决方案、预防清单
  • advanced-features.md - 2FA、组织管理、限流、Passkey、魔法链接、迁移指南
  • configuration-guide.md - 生产环境配置、环境变量、CORS、限流
  • framework-comparison.md - better-auth vs Clerk vs Auth.js对比、迁移路径、TCO
  • migration-guide-1.4.0.md - 从v1.3.x升级到v1.4.0+(ESM、API变更)
  • cloudflare-worker-drizzle.ts - 完整的Drizzle认证Worker实现
  • cloudflare-worker-kysely.ts - 完整的Kysely认证Worker实现
  • database-schema.ts - 完整的better-auth Drizzle Schema
  • react-client-hooks.tsx - 带认证钩子的React组件
  • v1.4-features.md - 后台任务、新OAuth提供商、SAML/SSO、CLI

Framework References (references/frameworks/)

框架参考文档(references/frameworks/)

  • nextjs.md - Next.js App/Pages Router integration
  • nuxt.md - Nuxt 3 with H3 and composables
  • remix.md - Remix loaders, actions, sessions
  • sveltekit.md - SvelteKit hooks and stores
  • api-frameworks.md - Express, Fastify, NestJS, Hono
  • expo-mobile.md - React Native and Expo
  • nextjs.md - Next.js App/Pages Router集成
  • nuxt.md - Nuxt 3与H3、组合式函数集成
  • remix.md - Remix loader、action、会话处理
  • sveltekit.md - SvelteKit钩子和状态存储
  • api-frameworks.md - Express、Fastify、NestJS、Hono
  • expo-mobile.md - React Native和Expo

Database References (references/databases/)

数据库参考文档(references/databases/)

  • postgresql.md - PostgreSQL with Drizzle/Prisma, Neon/Supabase
  • mongodb.md - MongoDB adapter and Atlas
  • mysql.md - MySQL and PlanetScale
  • postgresql.md - PostgreSQL与Drizzle/Prisma、Neon/Supabase
  • mongodb.md - MongoDB适配器和Atlas配置
  • mysql.md - MySQL和PlanetScale

Plugin References (references/plugins/)

插件参考文档(references/plugins/)

  • authentication.md - 2FA, passkeys, magic links, email OTP, anonymous
  • enterprise.md - Organizations, SSO, SCIM, admin
  • api-tokens.md - API keys, bearer tokens, JWT, OIDC
  • payments.md - Stripe, Polar integrations
  • authentication.md - 2FA、Passkey、魔法链接、邮箱OTP、匿名用户
  • enterprise.md - 组织、SSO、SCIM、管理员控制台
  • api-tokens.md - API密钥、Bearer令牌、JWT、OIDC
  • payments.md - Stripe、Polar集成

Next.js Examples (references/nextjs/)

Next.js示例(references/nextjs/)

  • README.md - Next.js + PostgreSQL setup guide (not D1)
  • postgres-example.ts - Complete API route with organizations, 2FA, email verification
  • README.md - Next.js + PostgreSQL安装指南(非D1)
  • postgres-example.ts - 完整的API路由实现,包含组织、2FA、邮箱验证

Client Integration

客户端集成

Create auth client (
src/lib/auth-client.ts
):
typescript
import { createAuthClient } from "better-auth/client";

export const authClient = createAuthClient({
  baseURL: import.meta.env.VITE_API_URL || "http://localhost:8787",
});
Use in React:
typescript
import { authClient } from "@/lib/auth-client";

export function UserProfile() {
  const { data: session, isPending } = authClient.useSession();

  if (isPending) return <div>Loading...</div>;
  if (!session) return <div>Not authenticated</div>;

  return (
    <div>
      <p>Welcome, {session.user.email}</p>
      <button onClick={() => authClient.signOut()}>Sign Out</button>
    </div>
  );
}

创建认证客户端
src/lib/auth-client.ts
):
typescript
import { createAuthClient } from "better-auth/client";

export const authClient = createAuthClient({
  baseURL: import.meta.env.VITE_API_URL || "http://localhost:8787",
});
在React中使用:
typescript
import { authClient } from "@/lib/auth-client";

export function UserProfile() {
  const { data: session, isPending } = authClient.useSession();

  if (isPending) return <div>加载中...</div>;
  if (!session) return <div>未认证</div>;

  return (
    <div>
      <p>欢迎,{session.user.email}</p>
      <button onClick={() => authClient.signOut()}>退出登录</button>
    </div>
  );
}

Dependencies

依赖项

Required:
  • better-auth@^1.4.9
    - Core authentication framework (ESM-only)
Choose ONE adapter:
  • drizzle-orm@^0.44.7
    +
    drizzle-kit@^0.31.7
    (recommended)
  • kysely@^0.28.8
    +
    @noxharmonium/kysely-d1@^0.4.0
    (alternative)
Optional:
  • @cloudflare/workers-types
    - TypeScript types for Workers
  • hono@^4.0.0
    - Web framework for routing
  • @better-auth/passkey
    - Passkey plugin (v1.4.0+, separate package)
  • @better-auth/api-key
    - API key auth (v1.4.0+)

必填:
  • better-auth@^1.4.9
    - 核心认证框架(仅支持ESM)
二选一适配器:
  • drizzle-orm@^0.44.7
    +
    drizzle-kit@^0.31.7
    (推荐)
  • kysely@^0.28.8
    +
    @noxharmonium/kysely-d1@^0.4.0
    (替代方案)
可选:
  • @cloudflare/workers-types
    - Workers的TypeScript类型定义
  • hono@^4.0.0
    - 用于路由的Web框架
  • @better-auth/passkey
    - Passkey插件(v1.4.0+,独立包)
  • @better-auth/api-key
    - API密钥认证(v1.4.0+)

Beyond Cloudflare D1

超越Cloudflare D1

This skill focuses on Cloudflare Workers + D1. better-auth also supports:
Frameworks (18 total): Next.js, Nuxt, Remix, SvelteKit, Astro, Express, NestJS, Fastify, Elysia, Expo, and more.
Databases (9 adapters): PostgreSQL, MongoDB, MySQL, Prisma, MS SQL, and others.
Additional Plugins: Anonymous auth, Email OTP, JWT, Multi-Session, OIDC Provider, payment integrations (Stripe, Polar).
For non-Cloudflare setups, load the appropriate framework or database reference file, or consult the official docs: https://better-auth.com/docs

本技能主要聚焦于Cloudflare Workers + D1。better-auth还支持:
框架(共18种):Next.js、Nuxt、Remix、SvelteKit、Astro、Express、NestJS、Fastify、Elysia、Expo等。
数据库(9种适配器):PostgreSQL、MongoDB、MySQL、Prisma、MS SQL等。
额外插件:匿名认证、邮箱OTP、JWT、多会话、OIDC提供商、支付集成(Stripe、Polar)。
非Cloudflare环境,请查看对应框架或数据库的参考文档,或访问官方文档:https://better-auth.com/docs

Official Documentation

官方文档

Framework Comparison

框架对比

Load
references/framework-comparison.md
for
:
  • Complete feature comparison: better-auth vs Clerk vs Auth.js
  • v1.4.0+ new features (database joins, stateless sessions, API keys)
  • Migration paths, cost analysis, and performance benchmarks
  • Recommendations by use case and 5-year TCO

查看
references/framework-comparison.md
获取以下内容
:
  • 完整功能对比:better-auth vs Clerk vs Auth.js
  • v1.4.0+新增功能(数据库关联、无状态会话、API密钥)
  • 迁移路径、成本分析、性能基准测试
  • 按使用场景推荐及5年TCO分析

Production Examples

生产示例

Verified working repositories (all use Drizzle or Kysely):
  1. zwily/example-react-router-cloudflare-d1-drizzle-better-auth - Drizzle
  2. matthewlynch/better-auth-react-router-cloudflare-d1 - Kysely
  3. foxlau/react-router-v7-better-auth - Drizzle
  4. zpg6/better-auth-cloudflare - Drizzle (includes CLI)
Note: Check each repo's better-auth version. Repos on v1.3.x need v1.4.0+ migration (see
references/migration-guide-1.4.0.md
). None use a direct
d1Adapter
- all require Drizzle/Kysely.

已验证可用的仓库(均使用Drizzle或Kysely):
  1. zwily/example-react-router-cloudflare-d1-drizzle-better-auth - Drizzle
  2. matthewlynch/better-auth-react-router-cloudflare-d1 - Kysely
  3. foxlau/react-router-v7-better-auth - Drizzle
  4. zpg6/better-auth-cloudflare - Drizzle(包含CLI)
注意:请检查每个仓库的better-auth版本。使用v1.3.x的仓库需要升级到v1.4.0+(查看
references/migration-guide-1.4.0.md
)。所有仓库均未使用直接的
d1Adapter
——全部需要Drizzle/Kysely。

Complete Setup Checklist

完整安装清单

  • Verified ESM support (
    "type": "module"
    in package.json) - v1.4.0+ required
  • Installed better-auth@1.4.9+ + Drizzle OR Kysely
  • Created D1 database with wrangler
  • Defined database schema with required tables (user, session, account, verification)
  • Generated and applied migrations to D1
  • Set BETTER_AUTH_SECRET environment variable
  • Configured baseURL in auth config
  • Enabled authentication methods (emailAndPassword, socialProviders)
  • Configured CORS with credentials: true
  • Set OAuth callback URLs in provider settings
  • Tested auth routes (/api/auth/*)
  • Tested sign-in, sign-up, session verification
  • Using requestPasswordReset (not forgetPassword) - v1.4.0+ API
  • Deployed to Cloudflare Workers

Questions? Issues?
  1. Check
    references/error-catalog.md
    for all 15 errors and solutions
  2. Review
    references/setup-guide.md
    for complete 8-step setup
  3. See
    references/advanced-features.md
    for 2FA, organizations, and more
  4. Check official docs: https://better-auth.com
  5. Ensure you're using Drizzle or Kysely (not non-existent d1Adapter)
  • 验证ESM支持(package.json中设置
    "type": "module"
    )- v1.4.0+必填
  • 安装better-auth@1.4.9+ + Drizzle 或 Kysely
  • 使用wrangler创建D1数据库
  • 定义包含必填表(user、session、account、verification)的数据库Schema
  • 生成并向D1应用数据库迁移
  • 设置BETTER_AUTH_SECRET环境变量
  • 在认证配置中设置baseURL
  • 启用认证方式(emailAndPassword、socialProviders)
  • 配置CORS并设置credentials: true
  • 在提供商设置中配置OAuth回调URL
  • 测试认证路由(/api/auth/*)
  • 测试登录、注册、会话验证
  • 使用requestPasswordReset替代forgetPassword - v1.4.0+ API
  • 部署到Cloudflare Workers

有疑问?遇到问题?
  1. 查看
    references/error-catalog.md
    获取所有15种错误及解决方案
  2. 查看
    references/setup-guide.md
    获取完整的8步安装指南
  3. 查看
    references/advanced-features.md
    获取2FA、组织管理等高级功能
  4. 访问官方文档:https://better-auth.com
  5. 确保使用Drizzle或Kysely(不存在d1Adapter)