选项
配置 Better Auth 的所有可用选项列表。请参阅 Better Auth 选项。
🌐 List of all the available options for configuring Better Auth. See Better Auth Options.
appName
应用的名称。
🌐 The name of the application.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
appName: "My App",
})baseURL
Better Auth 的基础 URL。通常这是托管你的应用服务器的根 URL。注意:如果你在 baseURL 中包含路径,它将优先于默认路径。
🌐 Base URL for Better Auth. This is typically the root URL where your application server is hosted. Note: If you include a path in the baseURL, it will take precedence over the default path.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
baseURL: "https://example.com",
})如果没有明确设置,系统将检查环境变量 BETTER_AUTH_URL。如果该变量也未设置,则将从传入请求中推断。
🌐 If not explicitly set, the system will check for the environment variable BETTER_AUTH_URL. If that's also not set, it will be inferred from the incoming request.
不建议依赖请求推断。为确保安全性和稳定性,请始终在配置中或通过 BETTER_AUTH_URL 环境变量显式设置 baseURL。
basePath
Better Auth 的基础路径。通常这是挂载 Better Auth 路由的路径。如果 baseURL 中包含路径组件,则此路径将被覆盖。
🌐 Base path for Better Auth. This is typically the path where the Better Auth routes are mounted. It will be overridden if there is a path component within baseURL.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
basePath: "/api/auth",
})默认:/api/auth
🌐 Default: /api/auth
trustedOrigins
受信任来源列表。你可以提供一个静态的来源数组,一个动态返回来源的函数,或者使用通配符模式来匹配多个域名。
🌐 List of trusted origins. You can provide a static array of origins, a function that returns origins dynamically, or use wildcard patterns to match multiple domains.
静态起源
🌐 Static Origins
你可以提供一个静态的来源数组:
🌐 You can provide a static array of origins:
import { betterAuth } from "better-auth";
export const auth = betterAuth({
trustedOrigins: ["http://localhost:3000", "https://example.com"],
})动态起源
🌐 Dynamic Origins
你可以提供一个动态返回来源的函数:
🌐 You can provide a function that returns origins dynamically:
export const auth = betterAuth({
trustedOrigins: async (request) => {
// request is undefined during initialization and auth.api calls
if (!request) {
return ["https://my-frontend.com"];
}
// Dynamic logic based on the request
return ["https://dynamic-origin.com"];
}
})在初始化时以及直接调用 auth.api 时,request 参数为 undefined。请确保通过返回默认可信来源来处理这种情况。
通配符支持
🌐 Wildcard Support
你可以在受信任的来源中使用通配符模式:
🌐 You can use wildcard patterns in trusted origins:
export const auth = betterAuth({
trustedOrigins: [
"https://*.example.com", // trust all HTTPS subdomains of example.com
"http://*.dev.example.com" // trust all HTTP subdomains of dev.example.com
]
})模式语法
🌐 Pattern Syntax
| 模式 | 描述 |
|---|---|
? | 匹配恰好一个字符(不包括 /) |
* | 匹配零个或多个不跨越 / 的字符 |
** | 匹配零个或多个包括 / 在内的字符 |
模式示例
🌐 Pattern Examples
| 模式 | 匹配 | 不匹配 |
|---|---|---|
http://*.example.com | http://api.example.comhttp://app.example.comhttp://api.app.example.com | https://api.example.comhttp://example.com |
https://**.example.com | https://api.example.comhttps://api.app.example.com | http://api.example.com |
https://example.com | https://example.comhttps://example.com/path | https://api.example.comhttp://example.com |
exp://192.168.*.*:*/** | exp://192.168.1.100:8081/pathexp://192.168.50.200:19000/auth/callback | exp://10.0.0.29:8081/path |
myapp:// | 所有以 myapp:// 开头的 URL | - |
注意事项
- 对于
http://和https://的 URL,模式匹配整个源。路径和查询字符串会被忽略。 - 对于自定义方案(如
exp://或myapp://),当存在通配符时,模式会与包括路径在内的完整 URL 匹配;如果没有通配符,则使用前缀匹配。 - 分隔符是
/(正斜杠)。这意味着http://*.example.com可以匹配http://api.example.com和http://api.app.example.com。
secret
用于加密、签名和哈希的密钥。
🌐 The secret used for encryption, signing, and hashing.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
secret: "your-secret-key",
})默认情况下,Better Auth 会查找以下环境变量:
🌐 By default, Better Auth will look for the following environment variables:
process.env.BETTER_AUTH_SECRETprocess.env.AUTH_SECRET
如果这些环境变量都未设置,它将默认为 "better-auth-secret-123456789"。在生产环境中,如果没有设置,它将抛出错误。
🌐 If none of these environment variables are set, it will default to "better-auth-secret-123456789". In production, if it's not set, it will throw an error.
你可以使用以下命令生成一个好的密码:
🌐 You can generate a good secret using the following command:
openssl rand -base64 32database
Better Auth 的数据库配置。
🌐 Database configuration for Better Auth.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
database: {
dialect: "postgres",
type: "postgres",
casing: "camel"
},
})Better Auth 支持多种数据库配置,包括 PostgreSQL、MySQL 和 SQLite。
🌐 Better Auth supports various database configurations including PostgreSQL, MySQL, and SQLite.
在此处阅读有关数据库的更多信息 here。
🌐 Read more about databases here.
secondaryStorage
用于存储会话和速率限制数据的二级存储配置。
🌐 Secondary storage configuration used to store session and rate limit data.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
// ... other options
secondaryStorage: {
// Your implementation here
},
})在此了解有关二级存储的更多信息 here。
🌐 Read more about secondary storage here.
emailVerification
电子邮件验证配置。
🌐 Email verification configuration.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
emailVerification: {
sendVerificationEmail: async ({ user, url, token }) => {
// Send verification email to user
},
sendOnSignUp: true,
autoSignInAfterVerification: true,
expiresIn: 3600 // 1 hour
},
})sendVerificationEmail:发送验证邮件的函数sendOnSignUp:注册后自动发送验证邮件(默认:false)sendOnSignIn:当用户的邮箱未验证时,在登录时自动发送验证邮件(默认值:false)autoSignInAfterVerification:在用户验证其电子邮件后自动登录expiresIn:验证令牌有效的秒数(默认值:3600秒)
emailAndPassword
电子邮件和密码认证配置。
🌐 Email and password authentication configuration.
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 }) => {
// Send reset password email
},
resetPasswordTokenExpiresIn: 3600, // 1 hour
password: {
hash: async (password) => {
// Custom password hashing
return hashedPassword;
},
verify: async ({ hash, password }) => {
// Custom password verification
return isValid;
}
}
},
})enabled:启用电子邮件和密码认证(默认值:false)disableSignUp:禁用邮箱和密码注册(默认:false)requireEmailVerification:在可以创建会话之前需要进行电子邮件验证minPasswordLength:最小密码长度(默认值:8)maxPasswordLength:最大密码长度(默认值:128)autoSignIn:注册后自动登录用户sendResetPassword:发送重置密码邮件的函数resetPasswordTokenExpiresIn:重置密码令牌的有效时间,单位为秒(默认:3600秒)password:自定义密码哈希和验证函数
socialProviders
配置社交登录提供商。
🌐 Configure social login providers.
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 客户端 IDclientSecret:来自提供商的 OAuth 客户端密钥clientKey:客户端密钥(由一些提供商使用,例如 TikTok,替代 clientId)(可选)redirectURI:OAuth 回调的自定义重定向 URI(可选)scope:请求的额外 OAuth 范围(可选)mapProfileToUser:将提供者配置文件映射到用户的自定义函数(可选)disableSignUp:禁用新用户注册(可选)disableImplicitSignUp:禁用新用户的自动注册(可选)overrideUserInfoOnSignIn: 在登录时用提供者的用户信息覆盖用户信息(可选)prompt:用于授权码请求的提示("select_account"、"consent"、"login"、"none"、"select_account consent")(可选)responseMode:要使用的响应模式("query"、"form_post")(可选)getUserInfo:用于从提供者获取用户信息的自定义函数(可选)refreshAccessToken:用于刷新令牌的自定义函数(可选)verifyIdToken:用于验证 ID 令牌的自定义函数(可选)disableIdTokenSignIn:禁用使用客户端发送的 ID 令牌登录(可选)disableDefaultScope:禁用提供者的默认权限范围(可选)authorizationEndpoint:自定义授权端点 URL(可选)
plugins
更好的认证插件列表。
🌐 List of Better Auth plugins.
import { betterAuth } from "better-auth";
import { emailOTP } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [
emailOTP({
sendVerificationOTP: async ({ email, otp, type }) => {
// Send OTP to user's email
}
})
],
})user
用户配置选项。
🌐 User configuration options.
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 }) => {
// Send change email confirmation to the old email
},
updateEmailWithoutVerification: false // Update email without verification if user is not verified
},
deleteUser: {
enabled: true,
sendDeleteAccountVerification: async ({ user, url, token }) => {
// Send delete account verification
},
beforeDelete: async (user) => {
// Perform actions before user deletion
},
afterDelete: async (user) => {
// Perform cleanup after user deletion
}
}
},
})modelName:用户的模型名称(默认值:“user”)fields:将字段映射到不同的列名additionalFields:用户表的附加字段changeEmail:更改电子邮件的配置deleteUser:用户删除的配置
session
会话配置选项。
🌐 Session configuration options.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
session: {
modelName: "sessions",
fields: {
userId: "user_id"
},
expiresIn: 604800, // 7 days
updateAge: 86400, // 1 day
disableSessionRefresh: true, // Disable session refresh so that the session is not updated regardless of the `updateAge` option. (default: `false`)
additionalFields: { // Additional fields for the session table
customField: {
type: "string",
}
},
storeSessionInDatabase: true, // Store session in database when secondary storage is provided (default: `false`)
preserveSessionInDatabase: false, // Preserve session records in database when deleted from secondary storage (default: `false`)
cookieCache: {
enabled: true, // Enable caching session in cookie (default: `false`)
maxAge: 300 // 5 minutes
}
},
})modelName:会话使用的模型名称(默认值:"session")fields:将字段映射到不同的列名expiresIn:会话令牌的过期时间,单位为秒(默认:604800- 7天)updateAge:会话应该以秒为单位刷新的频率(默认值:86400- 1天)additionalFields:会话表的附加字段storeSessionInDatabase:当提供了辅助存储时,将会话存储在数据库中(默认:false)preserveSessionInDatabase:当会话从二级存储中被删除时,保留数据库中的会话记录(默认值:false)cookieCache:启用在 cookie 中缓存会话
account
账户配置选项。
🌐 Account configuration options.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
account: {
modelName: "accounts",
fields: {
userId: "user_id"
},
encryptOAuthTokens: true, // Encrypt OAuth tokens before storing them in the database
storeAccountCookie: true, // Store account data after OAuth flow in a cookie (useful for database-less flows)
accountLinking: {
enabled: true,
trustedProviders: ["google", "github", "email-password"],
allowDifferentEmails: false
}
},
})modelName:账户的模型名称fields:将字段映射到不同的列名
encryptOAuthTokens
在将 OAuth 令牌存储到数据库之前进行加密。默认值:false。
🌐 Encrypt OAuth tokens before storing them in the database. Default: false.
updateAccountOnSignIn
如果启用(true),用户账户数据(accessToken、idToken、refreshToken 等)将在登录时使用来自提供者的最新数据进行更新。
🌐 If enabled (true), the user account data (accessToken, idToken, refreshToken, etc.) will be updated on sign in with the latest data from the provider.
storeAccountCookie
在 OAuth 流程后将账户数据存储在 cookie 中。这对于无需数据库的流程非常有用,在这种情况下,你可以将账户信息(访问令牌、刷新令牌等)存储在 cookie 中,而不是数据库中。
🌐 Store account data after OAuth flow in a cookie. This is useful for database-less flows where you want to store account information (access tokens, refresh tokens, etc.) in a cookie instead of the database.
- 默认:
false - 如果未提供数据库,则自动设置为
true
accountLinking
账户关联配置。
🌐 Configuration for account linking.
enabled:启用账户关联(默认:true)trustedProviders:受信任的提供者列表allowDifferentEmails:允许用户关联使用不同电子邮件的账户allowUnlinkingAll:允许用户取消关联所有账户
verification
验证配置选项。
🌐 Verification configuration options.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
verification: {
modelName: "verifications",
fields: {
userId: "user_id"
},
disableCleanup: false
},
})modelName:验证表的模型名称fields:将字段映射到不同的列名disableCleanup:在获取验证值时禁用清理过期值
rateLimit
速率限制配置。
🌐 Rate limiting configuration.
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
高级配置选项。
🌐 Advanced configuration options.
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 state configuration has been moved to account option
// Use account.storeStateStrategy and account.skipStateCookieCheck instead
cookiePrefix: "myapp",
database: {
// Use your own custom ID generator,
// disable generating IDS so your database will generate them,
// or use "serial" to use your database's auto-incrementing ID, or "uuid" to use a random UUID.
generateId: (((options: {
model: LiteralUnion<Models, string>;
size?: number;
}) => {
return "my-super-unique-id";
})) | false | "serial" | "uuid",
defaultFindManyLimit: 100,
experimentalJoins: false,
},
skipTrailingSlashes: true
},
})ipAddress:用于速率限制和会话跟踪的 IP 地址配置useSecureCookies:使用安全 Cookie(默认值:false)disableCSRFCheck:禁用所有 CSRF 保护,包括来源头验证和 Fetch 元数据检查(⚠️ 安全风险)disableOriginCheck:禁用callbackURL、redirectTo以及其他重定向 URL 的 URL 验证(⚠️ 存在安全风险)crossSubDomainCookies:配置跨子域共享的 Cookiecookies:自定义 cookie 名称和属性defaultCookieAttributes:所有 cookie 的默认属性cookiePrefix:Cookie 的前缀database:数据库配置选项skipTrailingSlashes:在路由匹配时跳过末尾斜杠的验证。(默认值:false)- OAuth 状态配置选项(
storeStateStrategy、skipStateCookieCheck)现在是account选项的一部分
logger
Better Auth 的日志记录配置。
🌐 Logger configuration for Better Auth.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
logger: {
disabled: false,
disableColors: false,
level: "error",
log: (level, message, ...args) => {
// Custom logging implementation
console.log(`[${level}] ${message}`, ...args);
}
}
})日志记录器配置允许你自定义 Better Auth 处理日志记录的方式。它支持以下选项:
🌐 The logger configuration allows you to customize how Better Auth handles logging. It supports the following options:
disabled:设置为true时禁用所有日志(默认值:false)disableColors:在默认日志记录器实现中禁用颜色(默认值:由终端的颜色支持情况决定)level:设置要显示的最低日志级别。可用的级别有:"info": 显示所有日志"warn": 显示警告和错误"error":仅显示错误debug:显示所有日志,包括调试信息
log:自定义日志函数,接收:level:日志级别("info"、"warn"、"error"或"debug")message: 日志信息...args:传递给日志记录器的其他参数
自定义日志示例:
🌐 Example with custom logging:
import { betterAuth } from "better-auth";
export const auth = betterAuth({
logger: {
level: "info",
log: (level, message, ...args) => {
// Send logs to a custom logging service
myLoggingService.log({
level,
message,
metadata: args,
timestamp: new Date().toISOString()
});
}
}
})databaseHooks
核心操作的数据库生命周期钩子。
🌐 Database lifecycle hooks for core operations.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
databaseHooks: {
user: {
create: {
before: async (user) => {
// Modify user data before creation
return { data: { ...user, customField: "value" } };
},
after: async (user) => {
// Perform actions after user creation
}
},
update: {
before: async (userData) => {
// Modify user data before update
return { data: { ...userData, updatedAt: new Date() } };
},
after: async (user) => {
// Perform actions after user update
}
}
},
session: {
// Session hooks
},
account: {
// Account hooks
},
verification: {
// Verification hooks
}
},
})onAPIError
API 错误处理配置。
🌐 API error handling configuration.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
onAPIError: {
throw: true,
onError: (error, ctx) => {
// Custom error handling
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
请求生命周期钩子。
🌐 Request lifecycle hooks.
import { betterAuth } from "better-auth";
import { createAuthMiddleware } from "better-auth/api";
export const auth = betterAuth({
hooks: {
before: createAuthMiddleware(async (ctx) => {
// Execute before processing the request
console.log("Request path:", ctx.path);
}),
after: createAuthMiddleware(async (ctx) => {
// Execute after processing the request
console.log("Response:", ctx.context.returned);
})
},
})有关更多详情和示例,请参阅 Hooks 文档。
🌐 For more details and examples, see the Hooks documentation.
disabledPaths
禁用特定的认证路径。
🌐 Disable specific auth paths.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
disabledPaths: ["/sign-up/email", "/sign-in/email"],
})telemetry
启用或禁用 Better Auth 的遥测数据收集。(默认值:false)
🌐 Enable or disable Better Auth's telemetry collection. (default: false)
import { betterAuth } from "better-auth";
export const auth = betterAuth({
telemetry: {
enabled: false,
}
})