基本用法
Better Auth 为以下内容提供内置认证支持:
- 电子邮件和密码
- 社交提供商(Google、GitHub、Apple 等)
但也可以通过插件轻松扩展,例如:username、magic link、passkey、email-otp 等。
电子邮件 & 密码
要启用电子邮件和密码认证:
import { betterAuth } from "better-auth"
export const auth = betterAuth({
emailAndPassword: {
enabled: true
}
})注册
要注册用户,您需要使用用户的个人信息调用客户端方法 signUp.email。
import { authClient } from "@/lib/auth-client"; //导入认证客户端
const { data, error } = await authClient.signUp.email({
email, // 用户电子邮件地址
password, // 用户密码 -> 默认最小 8 个字符
name, // 用户显示名称
image, // 用户图像 URL(可选)
callbackURL: "/dashboard" // 用户验证电子邮件后重定向的 URL(可选)
}, {
onRequest: (ctx) => {
//显示加载
},
onSuccess: (ctx) => {
//重定向到仪表板或登录页面
},
onError: (ctx) => {
// 显示错误消息
alert(ctx.error.message);
},
});默认情况下,用户在成功注册后会自动登录。要禁用此行为,您可以将 autoSignIn 设置为 false。
import { betterAuth } from "better-auth"
export const auth = betterAuth({
emailAndPassword: {
enabled: true,
autoSignIn: false //默认为 true
},
})登录
要登录用户,您可以使用客户端提供的 signIn.email 函数。
const { data, error } = await authClient.signIn.email({
/**
* 用户电子邮件
*/
email,
/**
* 用户密码
*/
password,
/**
* 用户验证电子邮件后重定向的 URL(可选)
*/
callbackURL: "/dashboard",
/**
* 在浏览器关闭后记住用户会话。
* @default true
*/
rememberMe: false
}, {
//回调
})始终从客户端调用客户端方法。不要从服务器调用它们。
服务器端认证
要在服务器上认证用户,您可以使用 auth.api 方法。
import { auth } from "./auth"; // 指向您的 Better Auth 服务器实例的路径
const response = await auth.api.signInEmail({
body: {
email,
password
},
asResponse: true // 返回响应对象而不是数据
});如果服务器无法返回响应对象,您需要手动解析和设置 Cookie。但对于 Next.js 等框架,我们提供 一个插件 来自动处理此操作
社交登录
Better Auth 支持多个社交提供商,包括 Google、GitHub、Apple、Discord 等。要使用社交提供商,您需要在 auth 对象的 socialProviders 选项中配置所需的提供商。
import { betterAuth } from "better-auth";
export const auth = betterAuth({
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}
},
})使用社交提供商登录
要使用社交提供商登录,您需要调用 signIn.social。它接受一个具有以下属性的对象:
import { authClient } from "@/lib/auth-client"; //导入认证客户端
await authClient.signIn.social({
/**
* 社交提供商 ID
* @example "github", "google", "apple"
*/
provider: "github",
/**
* 用户使用提供商认证后重定向的 URL
* @default "/"
*/
callbackURL: "/dashboard",
/**
* 登录过程中发生错误时重定向的 URL
*/
errorCallbackURL: "/error",
/**
* 用户新注册时重定向的 URL
*/
newUserCallbackURL: "/welcome",
/**
* 禁用自动重定向到提供商。
* @default false
*/
disableRedirect: true,
});您也可以使用来自社交提供商的 idToken 或 accessToken 进行认证,而不是将用户重定向到提供商的网站。有关更多详细信息,请参阅社交提供商文档。
登出
要登出用户,您可以使用客户端提供的 signOut 函数。
await authClient.signOut();您可以传递 fetchOptions 来在成功时重定向
await authClient.signOut({
fetchOptions: {
onSuccess: () => {
router.push("/login"); // 重定向到登录页面
},
},
});会话
一旦用户登录,您将想要访问用户会话。Better Auth 允许您轻松从服务器和客户端访问会话数据。
客户端
使用会话
Better Auth 提供了一个 useSession 钩子,以便在客户端轻松访问会话数据。此钩子使用 nanostore 实现,并支持每个支持的框架和纯客户端,确保会话的任何更改(例如登出)立即反映在您的 UI 中。
import { authClient } from "@/lib/auth-client" // 导入认证客户端
export function User(){
const {
data: session,
isPending, //加载状态
error, //错误对象
refetch //重新获取会话
} = authClient.useSession()
return (
//...
)
}<script setup lang="ts">
import { authClient } from "~/lib/auth-client"
const session = authClient.useSession()
</script>
<template>
<div>
<div>
<pre>{{ session.data }}</pre>
<button v-if="session.data" @click="authClient.signOut()">
登出
</button>
</div>
</div>
</template><script lang="ts">
import { authClient } from "$lib/auth-client";
const session = authClient.useSession();
</script>
<p>
{$session.data?.user.email}
</p>import { authClient } from "~/lib/auth-client"; //导入认证客户端
authClient.useSession.subscribe((value)=>{
//使用会话执行某些操作 //
}) import { authClient } from "~/lib/auth-client";
export default function Home() {
const session = authClient.useSession()
return (
<pre>{JSON.stringify(session(), null, 2)}</pre>
);
}获取会话
如果您不想使用钩子,您可以使用客户端提供的 getSession 方法。
import { authClient } from "@/lib/auth-client" // 导入认证客户端
const { data: session, error } = await authClient.getSession()您也可以将其与客户端数据获取库如 TanStack Query 一起使用。
服务器端
服务器提供了一个 session 对象,您可以使用它来访问会话数据。它需要将请求标头对象传递给 getSession 方法。
示例:使用一些流行框架
import { auth } from "./auth"; // 指向您的 Better Auth 服务器实例的路径
import { headers } from "next/headers";
const session = await auth.api.getSession({
headers: await headers() // 您需要传递标头对象。
})import { auth } from "lib/auth"; // 指向您的 Better Auth 服务器实例的路径
export async function loader({ request }: LoaderFunctionArgs) {
const session = await auth.api.getSession({
headers: request.headers
})
return json({ session })
}---
import { auth } from "./auth";
const session = await auth.api.getSession({
headers: Astro.request.headers,
});
---
<!-- 您的 Astro 模板 -->import { auth } from "./auth";
export async function load({ request }) {
const session = await auth.api.getSession({
headers: request.headers
})
return {
props: {
session
}
}
}import { auth } from "./auth";
const app = new Hono();
app.get("/path", async (c) => {
const session = await auth.api.getSession({
headers: c.req.raw.headers
})
});import { auth } from "~/utils/auth";
export default defineEventHandler((event) => {
const session = await auth.api.getSession({
headers: event.headers,
})
});import { auth } from "./auth";
import { createAPIFileRoute } from "@tanstack/start/api";
export const APIRoute = createAPIFileRoute("/api/$")({
GET: async ({ request }) => {
const session = await auth.api.getSession({
headers: request.headers
})
},
});有关更多详细信息,请查看 session-management 文档。
使用插件
Better Auth 的一个独特功能是插件生态系统。它允许您使用少量代码添加复杂的认证相关功能。
下面是一个使用双因素插件添加双因素认证的示例。
服务器配置
要添加插件,您需要导入插件并将其传递给认证实例的 plugins 选项。例如,要添加双因素认证,您可以使用以下代码:
import { betterAuth } from "better-auth"
import { twoFactor } from "better-auth/plugins"
export const auth = betterAuth({
//...其他选项
plugins: [
twoFactor()
]
})现在,双因素相关的路由和方法将在服务器上可用。
迁移数据库
添加插件后,您需要将必需的表添加到数据库中。您可以通过运行 migrate 命令来实现,或者使用 generate 命令创建架构并手动处理迁移。
生成架构:
npx @better-auth/cli generate使用 migrate 命令:
npx @better-auth/cli migrate如果您更喜欢手动添加架构,您可以在 双因素插件 文档中检查所需的架构。
客户端配置
完成服务器配置后,我们需要将插件添加到客户端。要实现此操作,您需要导入插件并将其传递给认证客户端的 plugins 选项。例如,要添加双因素认证,您可以使用以下代码:
import { createAuthClient } from "better-auth/client";
import { twoFactorClient } from "better-auth/client/plugins";
const authClient = createAuthClient({
plugins: [
twoFactorClient({
twoFactorPage: "/two-factor" // 如果用户需要验证第二因素,重定向的页面
})
]
})现在,双因素相关的方法将在客户端上可用。
import { authClient } from "./auth-client"
const enableTwoFactor = async() => {
const data = await authClient.twoFactor.enable({
password // 需要用户密码
}) // 这将启用双因素
}
const disableTwoFactor = async() => {
const data = await authClient.twoFactor.disable({
password // 需要用户密码
}) // 这将禁用双因素
}
const signInWith2Factor = async() => {
const data = await authClient.signIn.email({
//...
})
//如果用户启用了双因素,它将重定向到双因素页面
}
const verifyTOTP = async() => {
const data = await authClient.twoFactor.verifyTOTP({
code: "123456", // 用户输入的代码
/**
* 如果设备是受信任的,用户在同一设备上将无需再次通过 2FA
*/
trustDevice: true
})
}下一步:查看 双因素插件文档。