选项

Better Auth 配置选项参考。

Better Auth 配置的所有可用选项列表。详见 Better Auth Options

appName

你的应用名称。默认值为 "Better Auth"

它会在需要标识应用的场景中作为显示名称使用——例如,用户使用验证器应用(如 Google Authenticator)设置双因素认证时,appName 会作为 TOTP 条目中的发行方名称显示。该名称可按插件覆盖(例如 2FA 插件的 issuer 选项)。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	appName: "My App",
})

baseURL

Better Auth 的 Base URL。这通常是你的应用服务器托管的根 URL。你可以将其配置为以下任一形式:

  • 对于单域名部署:使用静态字符串
  • 对于跨多个允许主机的动态按请求解析:使用对象

如果你的 baseURL 字符串中包含路径组件,它将优先于默认路径。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	baseURL: "https://example.com",
})

如果未显式设置,系统将检查环境变量 BETTER_AUTH_URL。如果该环境变量也未设置,baseURL 将从传入请求中推断。

不建议依赖请求推断。出于安全性和稳定性考虑,请在配置中显式设置 baseURL,或通过 BETTER_AUTH_URL 环境变量进行设置。

动态 Base URL

当你的应用可以通过多个域名访问时(例如预览部署、分支环境或多个生产主机),请使用对象形式。Better Auth 会从传入请求中提取主机,使用 allowedHosts 校验,并基于该匹配构造与请求相关的 base URL。

import { betterAuth } from "better-auth";

export const auth = betterAuth({
	baseURL: {
		allowedHosts: [
			"myapp.com",
			"www.myapp.com",
			"*.vercel.app",
		],
		protocol: "https",
		fallback: "https://myapp.com",
	},
})
  • allowedHosts: 允许的主机模式列表。支持精确匹配(myapp.com)、通配符(*.vercel.apppreview-*.myapp.com)以及端口通配符(localhost:*)。会自动添加到 trustedOrigins(localhost 条目会同时加入 httphttps
  • protocol: 用于构造 URL 的协议。可为 "http""https""auto"(默认)。"auto" 会先从 x-forwarded-proto 读取,其次从请求 URL 推断,最后默认使用 HTTPS。该选项也会影响 cookie 的 Secure 标志:"https" → 安全,"http" → 不安全,"auto" 或未设置 → NODE_ENV === "production"。可通过 advanced.useSecureCookies 进行覆盖
  • fallback: 当传入主机不匹配时使用的 URL。若未设置,未知主机将会抛出错误。其来源也会被加入到 trustedOrigins

请谨慎使用 fallback。它可能会掩盖本应明显失败的部署或代理配置错误。

当启用 crossSubDomainCookies 时,cookie 域名会基于解析后的请求主机推导,除非你已显式设置 domain

有关部署模式和端到端示例,请参阅 Dynamic Base URL 指南

basePath

Better Auth 的基础路径。通常是挂载 Better Auth 路由的路径。如果 baseURL 中有路径组件,将会覆盖此项。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	basePath: "/api/auth",
})

默认值: /api/auth

trustedOrigins

默认情况下,Better Auth 会信任你应用的基础 URL(即 baseURL)。你可以通过此选项指定额外的可信来源。其值可以是静态来源数组、动态返回来源的函数,或用于匹配多个域名的通配符模式。

静态来源

你可以提供静态数组:

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	trustedOrigins: ["http://localhost:3000", "https://example.com"],
})

动态来源

也可以提供一个根据请求动态返回来源的函数:

export const auth = betterAuth({
	trustedOrigins: async (request) => {
		// 初始化和调用 auth.api 时 request 为 undefined
		if (!request) {
			return ["https://my-frontend.com"];
		}
		// 根据请求动态逻辑
		return ["https://dynamic-origin.com"];
	}
})

request 参数在初始化和直接调用 auth.api 时为 undefined。请确保处理此情况并返回默认可信来源。

通配符支持

可在可信来源中使用通配符模式:

export const auth = betterAuth({
	trustedOrigins: [
		"https://*.example.com", // 信任 example.com 的所有 HTTPS 子域
		"http://*.dev.example.com" // 信任 dev.example.com 的所有 HTTP 子域
	]
})

模式语法

PatternDescription
?匹配恰好一个字符(不包括 /
*匹配零个或多个不跨越 / 的字符
**匹配零个或多个字符(包括 /

模式示例

PatternMatchesDoes Not Match
http://*.example.comhttp://api.example.com
http://app.example.com
http://api.app.example.com
https://api.example.com
http://example.com
https://**.example.comhttps://api.example.com
https://api.app.example.com
http://api.example.com
https://example.comhttps://example.com
https://example.com/path
https://api.example.com
http://example.com
exp://192.168.*.*:*/**exp://192.168.1.100:8081/path
exp://192.168.50.200:19000/auth/callback
exp://10.0.0.29:8081/path
myapp://所有以 myapp:// 开头的 URL-

注意

  • 对于 http://https:// URL,模式匹配完整的来源(origin)。路径和查询字符串会被忽略。
  • 对于自定义协议(如 exp://myapp://),当通配符存在时,模式会与包含路径的完整 URL 进行匹配;当没有通配符时,则使用前缀匹配。
  • 分隔符是 /(正斜杠)。这意味着 http://*.example.com 会同时匹配 http://api.example.comhttp://api.app.example.com

secret

用于加密、签名和哈希的密钥。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	secret: "your-secret-key",
})

默认情况下,Better Auth 会查找以下环境变量:

  • process.env.BETTER_AUTH_SECRET

  • process.env.AUTH_SECRET

  • process.env.BETTER_AUTH_SECRET

  • process.env.AUTH_SECRET

如果两者都未设置,默认为 "better-auth-secret-12345678901234567890"。在生产环境中如果未设置将抛出错误。

你可以使用以下命令生成密钥:

openssl rand -base64 32

secrets

版本化密钥支持无破坏性密钥轮换。设置后,加密数据会使用带版本信息的信封格式,从而能够无缝轮换密钥且不影响现有数据。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	secrets: [
		{ version: 2, value: "new-secret-key" },
		{ version: 1, value: "old-secret-key" },
	],
})
  • 第一个条目是所有新加密使用的当前密钥。
  • 剩余条目是仅用于解密(之前的轮换)。
  • 版本为整数。允许存在空缺(例如在撤销 version 2 后,可能是 1, 3)。

也可通过 BETTER_AUTH_SECRETS 环境变量设置:

.env
BETTER_AUTH_SECRETS=2:new-secret-base64,1:old-secret-base64

设置 secrets 时,单个 secret 仅作为解密使用旧信封格式数据的备用。迁移期间,两者可以共存。

database

Better Auth 的数据库配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	database: {
		dialect: "postgres",
		type: "postgres",
		casing: "camel"
	},
})

Better Auth 支持多种数据库配置,包括 PostgreSQLMySQLSQLite

Read more about databases

secondaryStorage

用于存储会话数据、验证记录和速率限制数据的二级存储配置。

import { betterAuth } from "better-auth";

export const auth = betterAuth({
	// ... 其他选项
    secondaryStorage: {
    	// 你的实现
    },
})

Read more about secondary storage

emailVerification

邮箱验证配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	emailVerification: {
		sendVerificationEmail: async ({ user, url, token }) => {
			// 向用户发送验证邮件
		},
		sendOnSignUp: true,
		autoSignInAfterVerification: true,
		expiresIn: 3600 // 1 小时
	},
})
  • sendVerificationEmail: 发送验证邮件的函数
  • sendOnSignUp: 注册成功后自动发送验证邮件。true 总会发送,false 从不发送,undefined 将遵循 requireEmailVerification 的行为(默认:undefined
  • sendOnSignIn: 当用户登录且其邮箱尚未验证时,自动发送验证邮件(默认:false
  • autoSignInAfterVerification: 用户在验证邮箱后自动登录
  • expiresIn: 验证令牌的有效期(秒)(默认:3600 秒)

emailAndPassword

邮箱密码认证配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	emailAndPassword: {
		enabled: true,
		disableSignUp: false,
		requireEmailVerification: true,
		minPasswordLength: 8,
		maxPasswordLength: 128,
		autoSignIn: true,
		sendResetPassword: async ({ user, url, token }) => {
			// 发送重置密码邮件
		},
		resetPasswordTokenExpiresIn: 3600, // 1 小时
		password: {
			hash: async (password) => {
				// 自定义密码哈希
				return hashedPassword;
			},
			verify: async ({ hash, password }) => {
				// 自定义密码验证
				return isValid;
			}
		},
	},
})
  • enabled: 启用邮箱与密码认证(默认:false
  • disableSignUp: 禁用邮箱与密码注册(默认:false
  • requireEmailVerification: 在创建会话前要求进行邮箱验证
  • minPasswordLength: 最小密码长度(默认:8
  • maxPasswordLength: 最大密码长度(默认:128
  • autoSignIn: 用户注册后自动登录
  • sendResetPassword: 发送重置密码邮件的函数
  • onPasswordReset: 当用户密码成功更改时触发的回调
  • revokeSessionsOnPasswordReset: 重置密码时撤销所有其他会话(默认:false
  • resetPasswordTokenExpiresIn: 重置密码令牌的有效期(秒)(默认:3600 秒)
  • onExistingUserSignUp: 当有人使用已注册的邮箱进行注册时触发的回调。仅在 requireEmailVerificationtrueautoSignInfalse 时调用(默认:undefined)。
  • customSyntheticUser: 用于邮箱枚举防护的自定义合成用户构建函数。当插件向用户表添加字段时请使用。参见 邮箱枚举防护
  • password: 自定义密码哈希与验证函数

socialProviders

社交登录提供商配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	socialProviders: {
		google: {
			clientId: "your-client-id",
			clientSecret: "your-client-secret",
			redirectURI: "https://example.com/api/auth/callback/google"
		},
		github: {
			clientId: "your-client-id",
			clientSecret: "your-client-secret",
			redirectURI: "https://example.com/api/auth/callback/github"
		}
	},
})
  • clientId: 来自提供商的 OAuth 客户端 ID
  • clientSecret: 来自提供商的 OAuth 客户端密钥
  • clientKey: 客户端密钥(某些提供商如 TikTok 使用 clientKey 而不是 clientId)(可选)
  • redirectURI: OAuth 回调的自定义重定向 URI(可选)
  • scope: 额外需要请求的 OAuth scopes(可选)
  • mapProfileToUser: 自定义函数,将提供商的个人资料映射为用户(可选)
  • disableSignUp: 禁止新用户注册(可选)
  • disableImplicitSignUp: 禁止对新用户进行隐式注册(可选)
  • overrideUserInfoOnSignIn: 登录时用提供商的用户信息覆盖用户信息(可选)
  • prompt: 授权码请求所使用的提示("select_account", "consent", "login", "none", "select_account consent")(可选)
  • responseMode: 要使用的响应模式("query", "form_post")(可选)
  • getUserInfo: 自定义函数,从提供商获取用户信息(可选)
  • refreshAccessToken: 自定义函数,用于刷新令牌(可选)
  • verifyIdToken: 自定义函数,用于验证 ID token(可选)
  • disableIdTokenSignIn: 禁用使用客户端发送的 ID token 登录(可选)
  • disableDefaultScope: 禁用提供商的默认 scopes(可选)
  • authorizationEndpoint: 自定义授权端点 URL(可选)

plugins

Better Auth 插件列表。

import { betterAuth } from "better-auth";
import { emailOTP } from "better-auth/plugins";

export const auth = betterAuth({
	plugins: [
		emailOTP({
			sendVerificationOTP: async ({ email, otp, type }) => {
				// 向用户邮箱发送 OTP
			}
		})
	],
})

user

用户配置选项。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	user: {
		modelName: "users",
		fields: {
			email: "emailAddress",
			name: "fullName"
		},
		additionalFields: {
			customField: {
				type: "string",
			}
		},
		changeEmail: {
			enabled: true,
			sendChangeEmailConfirmation: async ({ user, newEmail, url, token }) => {
				// 向旧邮箱发送变更确认邮件
			},
			updateEmailWithoutVerification: false // 用户未验证时是否直接更新邮箱
		},
		deleteUser: {
			enabled: true,
			sendDeleteAccountVerification: async ({ user, url, token }) => {
				// 发送删除账号验证邮件
			},
			beforeDelete: async (user) => {
				// 删除用户前执行操作
			},
			afterDelete: async (user) => {
				// 删除用户后清理工作
			}
		}
	},
})
  • modelName: 用户的模型名称(默认:"user"
  • fields: 将字段映射到不同的列名
  • additionalFields: 用户表的附加字段
  • changeEmail: 更改邮箱的配置
  • deleteUser: 用户删除的配置

session

会话配置选项。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	session: {
		modelName: "sessions",
		fields: {
			userId: "user_id"
		},
		expiresIn: 604800, // 7 天
		updateAge: 86400, // 1 天
		disableSessionRefresh: true, // 禁用会话刷新,不根据 `updateAge` 更新会话(默认:`false`)
		additionalFields: { // 会话表额外字段
			customField: {
				type: "string",
			}
		},
		storeSessionInDatabase: true, // 提供二级存储时存数据库(默认:`false`)
		preserveSessionInDatabase: false, // 在二级存储删除后保留数据库中会话记录(默认:`false`)
		cookieCache: {
			enabled: true, // 启用 cookie 缓存会话(默认:`false`)
			maxAge: 300 // 5 分钟
		}
	},
})
  • modelName: 会话的模型名称(默认:"session"
  • fields: 将字段映射到不同的列名
  • expiresIn: 会话令牌过期时间(秒)(默认:604800 - 7 天)
  • updateAge: 会话需要刷新的频率(秒)(默认:86400 - 1 天)
  • additionalFields: 会话表的附加字段
  • storeSessionInDatabase: 在提供二级存储时,将会话存入数据库(默认:false
  • preserveSessionInDatabase: 当从二级存储删除会话时,在数据库中保留会话记录(默认:false
  • cookieCache: 启用在 cookie 中缓存会话

account

账号配置选项。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	account: {
		modelName: "accounts",
		fields: {
			userId: "user_id"
		},
		encryptOAuthTokens: true, // 在存入数据库前加密 OAuth 令牌
		storeStateStrategy: "database", // 将 OAuth 状态负载存储在验证存储中
		storeAccountCookie: true, // 在 OAuth 流程后将账号数据存入 cookie(适用于无数据库流程)
		accountLinking: {
			enabled: true,
			trustedProviders: ["google", "github", "email-password"], // 或异步函数 (request) => ["google", "github"]
			allowDifferentEmails: false
		},
	},
})
  • modelName: 账号的模型名称
  • fields: 将字段映射到不同的列名

encryptOAuthTokens

在存入数据库前加密 OAuth 令牌。默认为 false

updateAccountOnSignIn

启用后,登录时使用提供商最新数据(accessToken、idToken、refreshToken 等)更新用户账号。

storeStateStrategy

控制 OAuth 状态数据在认证流程中的存储位置。

  • "cookie":将状态负载存储在加密 cookie 中。这样 OAuth 状态保持无状态,并避免在流程开始时写入数据库。
  • "database":将状态负载存储在验证存储/表中,在开始流程时设置已签名的 state cookie,并在 OAuth 回调请求中将浏览器发送的已签名 cookie 与存储的状态进行校验。

如果配置了数据库,则默认值为 "database";对于无数据库/无状态设置,则默认为 "cookie"。如果你只提供了 secondaryStorage,请将其设为 "database",以便将 OAuth 状态存储在那里而不是 cookie 中。

storeAccountCookie

OAuth 流程后将账号数据(访问令牌、刷新令牌等)存入 cookie,适用于无数据库模式。

  • 默认值:false
  • 如果未提供数据库,会自动设置为 true

启用后,可以通过 better-auth/cookiesgetAccountCookie 在钩子或中间件中读取解密后的账号 cookie:

import { createAuthMiddleware } from "better-auth/api";
import { getAccountCookie } from "better-auth/cookies";

const hook = createAuthMiddleware(async (ctx) => {
	const account = await getAccountCookie(ctx);
});

accountLinking

账号关联配置。

  • enabled: 启用账号关联(默认:true
  • trustedProviders: 受信任的提供商列表。可以是静态数组,也可以是异步函数,该函数基于请求动态返回提供商(类似 trustedOrigins
  • allowDifferentEmails: 允许用户使用不同邮箱地址来关联账号
  • allowUnlinkingAll: 允许用户解除所有关联账号的解绑

verification

验证相关配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	secondaryStorage: {
		// 你的 Redis 或 KV 实现
	},
	verification: {
		disableCleanup: false,
		storeIdentifier: "hashed",
		storeInDatabase: false
	},
})
  • modelName: 验证表的模型名称
  • fields: 将字段映射到不同的列名
  • disableCleanup: 当获取某个验证值时,禁用清理过期值
  • storeIdentifier: 如何存储诸如 token 和 OTP key 之类的验证标识符。支持 "plain", "hashed" 或自定义哈希器。你也可以使用 { default, overrides } 来对每个标识符前缀应用不同策略。
  • storeInDatabase: 即使配置了 secondaryStorage,也将验证记录存入数据库。默认值:false

如果配置了 secondaryStorage,验证记录默认存储在二级存储中。此行为适用于使用 Better Auth 共享验证层的流程,包括 OTP 和魔法链接(magic-link)风格的流程。

rateLimit

速率限制配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	rateLimit: {
		enabled: true,
		window: 10,
		max: 100,
		customRules: {
			"/example/path": {
				window: 10,
				max: 100
			}
		},
		storage: "memory",
		modelName: "rateLimit"
	}
})
  • enabled: 启用速率限制(生产环境默认:true,开发环境默认:false
  • window: 用于速率限制的时间窗口。该值应以秒为单位。(默认:10
  • max: 在时间窗口内允许的默认最大请求数。(默认:100
  • customRules: 为特定路径应用的自定义速率限制规则。
  • storage: 存储配置。如果你提供了二级存储,速率限制将存储在二级存储中。(选项:"memory", "database", "secondary-storage",默认:"memory"
  • modelName: 当数据库用作存储时,速率限制所使用的表名。(默认:"rateLimit"

advanced

高级配置选项。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	advanced: {
		ipAddress: {
			ipAddressHeaders: ["x-client-ip", "x-forwarded-for"],
			disableIpTracking: false
		},
		useSecureCookies: true,
		disableCSRFCheck: false,
		disableOriginCheck: false,
		crossSubDomainCookies: {
			enabled: true,
			additionalCookies: ["custom_cookie"],
			domain: "example.com"
		},
		cookies: {
			session_token: {
				name: "custom_session_token",
				attributes: {
					httpOnly: true,
					secure: true
				}
			}
		},
		defaultCookieAttributes: {
			httpOnly: true,
			secure: true
		},
		// OAuth 状态配置已移至 account 选项
		// 使用 account.storeStateStrategy 和 account.skipStateCookieCheck
		cookiePrefix: "myapp",
		database: {
			// 自定义 ID 生成器,
			// 禁用生成 ID,让数据库自动生成,
			// 或使用 "serial" 使用数据库自增 ID,或 "uuid" 使用随机 UUID。
			generateId: (((options: {
				model: LiteralUnion<Models, string>;
				size?: number;
			}) => {
				return "my-super-unique-id";
			})) | false | "serial" | "uuid",
			defaultFindManyLimit: 100,
			experimentalJoins: false,
		},
		backgroundTasks: {
			handler: (promise) => { /* 如 waitUntil(promise) */ }
		},
		skipTrailingSlashes: true
	},
})
  • ipAddress: 用于速率限制和会话跟踪的 IP 地址配置
  • useSecureCookies: 默认情况下,在生产环境中 cookie 是安全的。设置为 true 以强制在所有环境中使用 Secure cookie 属性。
  • disableCSRFCheck: 禁用所有 CSRF 保护,包括 origin 头验证和 Fetch Metadata 检查(⚠️ 安全风险)
  • disableOriginCheck: 禁用对 callbackURLredirectTo 以及其他重定向 URL 的校验(⚠️ 安全风险)
  • crossSubDomainCookies: 配置 cookie 在子域之间共享
  • cookies: 自定义 cookie 名称和属性
  • defaultCookieAttributes: 所有 cookie 的默认属性
  • cookiePrefix: cookie 前缀
  • database: 数据库配置选项
  • backgroundTasks: 配置后台任务处理,用于延迟操作
  • skipTrailingSlashes: 在路由匹配中跳过尾部斜杠校验。(默认:false
  • OAuth 状态配置选项(storeStateStrategy, skipStateCookieCheck)现已属于 account 选项

database

为 ID 生成和 findMany 查询设置自定义策略。

  • generateId: 控制记录 ID 的生成方式。接受自定义函数、false"serial""uuid"(默认:随机 base62 字符串)。更多信息请参阅数据库文档
  • defaultFindManyLimit: findMany 适配器方法返回的默认最大记录数。(默认:100
import { betterAuth } from "better-auth";

export const auth = betterAuth({
	advanced: {
		database: {
			generateId: "uuid",
			defaultFindManyLimit: 50,
		},
	},
});

backgroundTasks

用于配置延迟操作的后台任务处理。后台任务允许非关键操作(如清理、分析、时序攻击缓解或速率限制计数更新)在响应发送后执行,显著提升无服务器平台的响应速度。

例如:在 Vercel 上使用 @vercel/functionswaitUntil,或 Cloudflare Workers 上的 ctx.waitUntil。详见下面示例。

启用该功能会引入最终一致性,即响应返回的是乐观数据,数据库尚未更新。仅当你的应用能接受此权衡以换取延迟优化时启用。

import { betterAuth } from "better-auth";
import { waitUntil } from "@vercel/functions";

export const auth = betterAuth({
  advanced: {
    backgroundTasks: {
      handler: waitUntil,
    },
  },
});
import { betterAuth } from "better-auth";
import { AsyncLocalStorage } from "node:async_hooks";

const execCtxStorage = new AsyncLocalStorage<ExecutionContext>();

export const auth = betterAuth({
  advanced: {
    backgroundTasks: {
      handler: (p) => execCtxStorage.getStore()?.waitUntil(p),
    },
  },
});

// 在请求处理时用 execCtxStorage.run(ctx, ...) 包裹

logger

Better Auth 的日志配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	logger: {
		disabled: false,
		disableColors: false,
		level: "warn",
		log: (level, message, ...args) => {
			// 自定义日志实现
			console.log(`[${level}] ${message}`, ...args);
		}
	}
})

该配置允许定制 Better Auth 的日志行为,支持选项包括:

  • disabled: 在设置为 true 时禁用所有日志输出(默认:false
  • disableColors: 禁用默认日志实现中的颜色(默认:由终端的颜色支持情况决定)
  • level: 设置要显示的最低日志级别(默认:"warn"
    • "debug": 显示所有日志,包括调试信息
    • "info": 显示所有日志,但不包含调试信息
    • "warn": 显示警告和错误
    • "error": 仅显示错误
  • log: 自定义日志函数,接收:
    • level: 日志级别
    • message: 日志消息
    • ...args: 传递给日志器的其他参数

自定义日志示例:

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	logger: {
		level: "info",
		log: (level, message, ...args) => {
			// 将日志发送到自定义日志服务
			myLoggingService.log({
				level,
				message,
				metadata: args,
				timestamp: new Date().toISOString()
			});
		}
	}
})

databaseHooks

核心操作的数据库生命周期钩子。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	databaseHooks: {
		user: {
			create: {
				before: async (user) => {
					// 创建用户前修改数据
					return { data: { ...user, customField: "value" } };
				},
				after: async (user) => {
					// 创建用户后执行操作
				}
			},
			update: {
				before: async (userData) => {
					// 更新用户前修改数据
					return { data: { ...userData, updatedAt: new Date() } };
				},
				after: async (user) => {
					// 更新用户后执行操作
				}
			}
		},
		session: {
			// 会话钩子
		},
		account: {
			// 账号钩子
		},
		verification: {
			// 验证钩子
		}
	},
})

onAPIError

API 错误处理配置。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	onAPIError: {
		throw: true,
		onError: (error, ctx) => {
			// 自定义错误处理
			console.error("Auth error:", error);
		},
		errorURL: "/auth/error",
		customizeDefaultErrorPage: {
			colors: {
				background: "#ffffff",
				foreground: "#000000",
				primary: "#0070f3",
				primaryForeground: "#ffffff",
				mutedForeground: "#666666",
				border: "#e0e0e0",
				destructive: "#ef4444",
				titleBorder: "#0070f3",
				titleColor: "#000000",
				gridColor: "#f0f0f0",
				cardBackground: "#ffffff",
				cornerBorder: "#0070f3"
			},
			size: {
				radiusSm: "0.25rem",
				radiusMd: "0.5rem",
				radiusLg: "1rem",
				textSm: "0.875rem",
				text2xl: "1.5rem",
				text4xl: "2.25rem",
				text6xl: "3.75rem"
			},
			font: {
				defaultFamily: "system-ui, sans-serif",
				monoFamily: "monospace"
			},
			disableTitleBorder: false,
			disableCornerDecorations: false,
			disableBackgroundGrid: false
		}
	},
})
  • throw: 发生 API 错误时抛出异常(默认:false
  • onError: 自定义错误处理函数
  • errorURL: 发生错误时重定向的 URL(默认:/api/auth/error
  • customizeDefaultErrorPage: 配置 Better Auth 提供的默认错误页面。启动开发服务器并访问 /api/auth/error 查看错误页面。
    • colors: 自定义错误页面的配色方案
      • background: 背景颜色
      • foreground: 前景/文本颜色
      • primary: 主要强调色
      • primaryForeground: 主要背景上的文本颜色
      • mutedForeground: 弱化文本颜色
      • border: 边框颜色
      • destructive: 错误/破坏性颜色
      • titleBorder: 标题的边框颜色
      • titleColor: 标题文本颜色
      • gridColor: 背景网格颜色
      • cardBackground: 卡片背景颜色
      • cornerBorder: 角落装饰的边框颜色
    • size: 自定义尺寸和间距
      • radiusSm: 小边框半径
      • radiusMd: 中等边框半径
      • radiusLg: 大边框半径
      • textSm: 小文本大小
      • text2xl: 2xl 文本大小
      • text4xl: 4xl 文本大小
      • text6xl: 6xl 文本大小
    • font: 自定义字体族
      • defaultFamily: 默认字体族
      • monoFamily: 等宽字体族
    • disableTitleBorder: 禁用标题周围的边框(默认:false
    • disableCornerDecorations: 禁用角落装饰(默认:false
    • disableBackgroundGrid: 禁用背景网格图案(默认:false

hooks

请求生命周期钩子。

import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";

export const auth = betterAuth({
	hooks: {
		before: createAuthMiddleware(async (ctx) => {
			// 请求处理前执行
			console.log("Request path:", ctx.path);
		}),
		after: createAuthMiddleware(async (ctx) => {
			// 请求处理后执行
			console.log("Response:", ctx.context.returned);
		})
	},
})

更多详情和示例见 钩子文档

disabledPaths

禁用特定的 auth 路径。

import { betterAuth } from "better-auth";
export const auth = betterAuth({
	disabledPaths: ["/sign-up/email", "/sign-in/email"],
})

telemetry

启用或禁用 Better Auth 的遥测收集。(默认:false

import { betterAuth } from "better-auth";
export const auth = betterAuth({
  telemetry: {
    enabled: false,
  }
})