客户端
Better Auth 提供了一个与流行前端框架(如 React、Vue、Svelte 等)兼容的客户端库。该客户端库包括一组用于与 Better Auth 服务器交互的函数。每个框架的客户端库都是基于一个与框架无关的核心客户端库构建的,因此所有方法和钩子在所有客户端库中都可以一致使用。
【Better Auth offers a client library compatible with popular frontend frameworks like React, Vue, Svelte, and more. This client library includes a set of functions for interacting with the Better Auth server. Each framework's client library is built on top of a core client library that is framework-agnostic, so that all methods and hooks are consistently available across all client libraries.】
安装
【Installation】
如果你还没安装,请安装 better-auth。
【If you haven't already, install better-auth.】
npm i better-auth创建客户端实例
【Create Client Instance】
从你的框架对应的包中导入 createAuthClient(例如,React 使用 "better-auth/react")。调用该函数来创建你的客户端。传入你的认证服务器的基础 URL。如果认证服务器与客户端运行在同一域上,你可以跳过这一步。
【Import createAuthClient from the package for your framework (e.g., "better-auth/react" for React). Call the function to create your client. Pass the base URL of your auth server. If the auth server is running on the same domain as your client, you can skip this step.】
如果你使用的基路径不是 /api/auth,请确保传递完整的 URL,包括路径。(例如:http://localhost:3000/custom-path/auth)
import { createAuthClient } from "better-auth/client"
export const authClient = createAuthClient({
baseURL: "http://localhost:3000" // The base URL of your auth server
})import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
baseURL: "http://localhost:3000" // The base URL of your auth server
})import { createAuthClient } from "better-auth/vue"
export const authClient = createAuthClient({
baseURL: "http://localhost:3000" // The base URL of your auth server
})import { createAuthClient } from "better-auth/svelte"
export const authClient = createAuthClient({
baseURL: "http://localhost:3000" // The base URL of your auth server
})import { createAuthClient } from "better-auth/solid"
export const authClient = createAuthClient({
baseURL: "http://localhost:3000" // The base URL of your auth server
})用法
【Usage】
一旦你创建了客户端实例,就可以使用该客户端与 Better Auth 服务器进行交互。客户端默认提供一组功能,并且可以通过插件进行扩展。
【Once you've created your client instance, you can use the client to interact with the Better Auth server. The client provides a set of functions by default and they can be extended with plugins.】
示例:登录
import { createAuthClient } from "better-auth/client"
const authClient = createAuthClient()
await authClient.signIn.email({
email: "test@user.com",
password: "password1234"
})钩子
【Hooks】
除了标准方法之外,客户端还提供了钩子,以便轻松访问不同的响应式数据。每个钩子都可以在客户端的根对象中使用,并且它们都以 use 开头。
【In addition to the standard methods, the client provides hooks to easily access different reactive data. Every hook is available in the root object of the client and they all start with use.】
示例:useSession
//make sure you're using the react client
import { createAuthClient } from "better-auth/react"
const { useSession } = createAuthClient()
export function User() {
const {
data: session,
isPending, //loading state
error, //error object
refetch //refetch the session
} = useSession()
return (
//...
)
}<script lang="ts" setup>
import { authClient } from '@/lib/auth-client'
const session = authClient.useSession()
</script>
<template>
<div>
<button v-if="!session.data" @click="() => authClient.signIn.social({
provider: 'github'
})">
Continue with GitHub
</button>
<div>
<pre>{{ session.data }}</pre>
<button v-if="session.data" @click="authClient.signOut()">
Sign out
</button>
</div>
</div>
</template><script lang="ts">
import { authClient } from "$lib/auth-client";
const session = authClient.useSession();
</script>
<div
style="display: flex; flex-direction: column; gap: 10px; border-radius: 10px; border: 1px solid #4B453F; padding: 20px; margin-top: 10px;"
>
<div>
{#if $session.data}
<div>
<p>
{$session.data.user.name}
</p>
<p>
{$session.data.user.email}
</p>
<button
onclick={async () => {
await authClient.signOut();
}}
>
Signout
</button>
</div>
{:else}
<button
onclick={async () => {
await authClient.signIn.social({
provider: "github",
});
}}
>
Continue with GitHub
</button>
{/if}
</div>
</div>import { authClient } from "~/lib/auth-client";
import { Show } from 'solid-js';
export default function Home() {
const session = authClient.useSession()
return (
<Show
when={session()}
fallback={<button onClick={toggle}>Log in</button>}
>
<button onClick={toggle}>Log out</button>
</Show>
);
}获取选项
【Fetch Options】
客户端使用一个名为 better fetch 的库向服务器发起请求。
【The client uses a library called better fetch to make requests to the server. 】
Better fetch 是对原生 fetch API 的一个封装,提供了更方便的请求方式。它由开发 Better Auth 的同一团队创建,并旨在与其无缝协作。
【Better fetch is a wrapper around the native fetch API that provides a more convenient way to make requests. It's created by the same team behind Better Auth and is designed to work seamlessly with it.】
你可以通过向 createAuthClient 传递 fetchOptions 对象,将任何默认的 fetch 选项传递给客户端。
【You can pass any default fetch options to the client by passing fetchOptions object to the createAuthClient.】
import { createAuthClient } from "better-auth/client"
const authClient = createAuthClient({
fetchOptions: {
//any better-fetch options
},
})你也可以将 fetch 选项传递给大多数客户端函数。可以作为第二个参数传递,或者作为对象中的一个属性传递。
【You can also pass fetch options to most of the client functions. Either as the second argument or as a property in the object.】
await authClient.signIn.email({
email: "email@email.com",
password: "password1234",
}, {
onSuccess(ctx) {
//
}
})
//or
await authClient.signIn.email({
email: "email@email.com",
password: "password1234",
fetchOptions: {
onSuccess(ctx) {
//
}
},
})禁用 Hook 重渲染
【Disabling Hook Rerenders】
某些端点在成功响应后会触发原子信号,并导致像 useSession 这样的钩子重新渲染。这对于保持用户界面与身份验证状态的同步非常有用。
【Certain endpoints, upon successful response, will trigger atom signals and cause hooks like useSession to rerender.
This is useful for keeping your UI in sync with authentication state changes.】
然而,有些情况下你可能希望调用端点而不触发钩子重新渲染。例如,在更新不会影响会话的用户偏好设置时,或者当你想手动控制钩子的更新时。
【However, there are cases where you might want to make an endpoint call without triggering hook rerenders. For example, when updating user preferences that don't affect the session, or when you want to manually control when hooks update.】
你可以通过在 fetch 选项中设置 disableSignal: true,来禁用特定端点调用的 hook 重新渲染:
【You can disable hook rerenders for a specific endpoint call by setting disableSignal: true in the fetch options:】
// As the second argument
await authClient.updateUser({
name: "New Name"
}, {
disableSignal: true
})
// Or within fetchOptions
await authClient.updateUser({
name: "New Name",
fetchOptions: {
disableSignal: true
}
})当 disableSignal 设置为 true 时,端点调用将成功完成,但像 useSession 这样的钩子不会自动重新渲染。如果需要,你可以手动触发重新获取数据:
【When disableSignal is set to true, the endpoint call will complete successfully,
but hooks like useSession won't automatically rerender. You can manually trigger a refetch if needed:】
const { refetch } = authClient.useSession()
await authClient.updateUser({
name: "New Name"
}, {
disableSignal: true,
onSuccess() {
// Manually refetch session if needed
refetch()
}
})错误处理
【Handling Errors】
大多数客户端函数返回一个具有以下属性的响应对象:
data:响应数据。error:如果发生错误,则返回错误对象。
【Most of the client functions return a response object with the following properties:
data: The response data.error: The error object if there was an error.】
错误对象包含以下属性:
message:错误信息。(例如,“电子邮件或密码无效”)status:HTTP 状态码。statusText:HTTP 状态文本。
【The error object contains the following properties:
message: The error message. (e.g., "Invalid email or password")status: The HTTP status code.statusText: The HTTP status text.】
const { data, error } = await authClient.signIn.email({
email: "email@email.com",
password: "password1234"
})
if (error) {
//handle error
}如果该操作接受 fetchOptions 选项,你可以传入 onError 回调来处理错误。
【If the action accepts a fetchOptions option, you can pass an onError callback to handle errors.】
await authClient.signIn.email({
email: "email@email.com",
password: "password1234",
}, {
onError(ctx) {
//handle error
}
})
//or
await authClient.signIn.email({
email: "email@email.com",
password: "password1234",
fetchOptions: {
onError(ctx) {
//handle error
}
}
})像 useSession 这样的 Hooks 如果在获取会话时出错,也会返回一个错误对象。此外,它们还会返回一个 isPending 属性,用来表示请求是否仍在处理中。
【Hooks like useSession also return an error object if there was an error fetching the session. On top of that, they also return an isPending property to indicate if the request is still pending.】
const { data, error, isPending } = useSession()
if (error) {
//handle error
}错误代码
【Error Codes】
客户端实例包含 $ERROR_CODES 对象,里面包含服务器返回的所有错误代码。你可以使用它来处理错误翻译或自定义错误消息。
【The client instance contains $ERROR_CODES object that contains all the error codes returned by the server. You can use this to handle error translations or custom error messages.】
const authClient = createAuthClient();
type ErrorTypes = Partial<
Record<
keyof typeof authClient.$ERROR_CODES,
{
en: string;
es: string;
}
>
>;
const errorCodes = {
USER_ALREADY_EXISTS: {
en: "user already registered",
es: "usuario ya registrado",
},
} satisfies ErrorTypes;
const getErrorMessage = (code: string, lang: "en" | "es") => {
if (code in errorCodes) {
return errorCodes[code as keyof typeof errorCodes][lang];
}
return "";
};
const { error } = await authClient.signUp.email({
email: "user@email.com",
password: "password",
name: "User",
});
if(error?.code){
alert(getErrorMessage(error.code, "en"));
}插件
【Plugins】
你可以通过插件扩展客户端,以增加更多功能。插件可以为客户端添加新功能或修改现有功能。
【You can extend the client with plugins to add more functionality. Plugins can add new functions to the client or modify existing ones. 】
示例:魔法链接插件
import { createAuthClient } from "better-auth/client"
import { magicLinkClient } from "better-auth/client/plugins"
const authClient = createAuthClient({
plugins: [
magicLinkClient()
]
})一旦你添加了插件,你就可以使用插件提供的新功能。
【once you've added the plugin, you can use the new functions provided by the plugin.】
await authClient.signIn.magicLink({
email: "test@email.com"
})