客户端

Better Auth 提供与主流前端框架(如 React、Vue、Svelte 等)兼容的客户端库。该客户端库包含一系列用于与 Better Auth 服务器交互的函数。每个框架的客户端库都构建在一个与框架无关的核心客户端库之上,因此所有方法和钩子(hooks)在所有客户端库中都能保持一致可用。

安装

如果尚未安装,请先安装 better-auth。

npm i better-auth

创建客户端实例

从适用于您框架的包中导入 createAuthClient(例如,React 使用 "better-auth/react")。调用该函数来创建您的客户端。传入您认证服务器的基本 URL。如果认证服务器与您的客户端运行在同一域上,则可以跳过此步骤。

如果您使用的不是默认的 /api/auth 路径,请确保传入完整的 URL,包括路径。(例如:http://localhost:3000/custom-path/auth

lib/auth-client.ts
import { createAuthClient } from "better-auth/client"
export const authClient = createAuthClient({
    baseURL: "http://localhost:3000" // 您的认证服务器的基本 URL
})
lib/auth-client.ts
import { createAuthClient } from "better-auth/react"
export const authClient = createAuthClient({
    baseURL: "http://localhost:3000" // 您的认证服务器的基本 URL
})
lib/auth-client.ts
import { createAuthClient } from "better-auth/vue"
export const authClient = createAuthClient({
    baseURL: "http://localhost:3000" // 您的认证服务器的基本 URL
})
lib/auth-client.ts
import { createAuthClient } from "better-auth/svelte"
export const authClient = createAuthClient({
    baseURL: "http://localhost:3000" // 您的认证服务器的基本 URL
})
lib/auth-client.ts
import { createAuthClient } from "better-auth/solid"
export const authClient = createAuthClient({
    baseURL: "http://localhost:3000" // 您的认证服务器的基本 URL
})

使用方法

创建客户端实例后,您可以使用该客户端与 Better Auth 服务器进行交互。客户端默认提供一组功能,并且可以通过插件进行扩展。

示例:登录

auth-client.ts
import { createAuthClient } from "better-auth/client"
const authClient = createAuthClient()

await authClient.signIn.email({
    email: "test@user.com",
    password: "password1234"
})

钩子函数

除了常规方法外,客户端还提供了钩子函数以便轻松访问不同的响应式数据。所有钩子函数都位于客户端的根对象中,并且都以 use 开头。

示例:useSession 使用

user.tsx
// 确保你正在使用 React 客户端
import { createAuthClient } from "better-auth/react"
const { useSession } = createAuthClient() 

export function User() {
    const {
        data: session,
        isPending, // 加载状态
        error, // 错误对象
        refetch // 重新获取会话
    } = useSession()
    return (
        //...
    )
}
user.vue
<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'
        })">
            使用 GitHub 继续
        </button>
        <div>
            <pre>{{ session.data }}</pre>
            <button v-if="session.data" @click="authClient.signOut()">
                退出登录
            </button>
        </div>
    </div>
</template>
user.svelte
<script lang="ts">
import { client } from "$lib/client";
const session = client.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}
        <div>
        <p>
            {$session?.data?.user.name}
        </p>
        <p>
            {$session?.data?.user.email}
        </p>
        <button
            on:click={async () => {
            await authClient.signOut();
            }}
        >
            退出登录
        </button>
        </div>
    {:else}
        <button
        on:click={async () => {
            await authClient.signIn.social({
            provider: "github",
            });
        }}
        >
        使用 GitHub 继续
        </button>
    {/if}
    </div>
</div>
user.tsx
import { client } from "~/lib/client";
import { Show } from 'solid-js';

export default function Home() {
    const session = client.useSession()
    return (
        <Show
            when={session()}
            fallback={<button onClick={toggle}>登录</button>}
        >
            <button onClick={toggle}>退出登录</button>
        </Show>
    );
}

Fetch 选项

客户端使用名为 better fetch 的库向服务器发起请求。

Better fetch 是对原生 fetch API 的封装,提供了更便捷的请求方式。它由 Better Auth 背后的同一团队创建,并设计为与 Better Auth 无缝协作。

你可以通过向 createAuthClient 传递 fetchOptions 对象来配置客户端的默认 fetch 选项。

auth-client.ts
import { createAuthClient } from "better-auth/client"

const authClient = createAuthClient({
    fetchOptions: {
        // 任意 better-fetch 选项
    },
})

你也可以向大多数客户端函数传递 fetch 选项。可以作为第二个参数传递,也可以作为对象中的一个属性传递。

auth-client.ts
await authClient.signIn.email({
    email: "email@email.com",
    password: "password1234",
}, {
    onSuccess(ctx) {
            //
    }
})

// 或者

await authClient.signIn.email({
    email: "email@email.com",
    password: "password1234",
    fetchOptions: {
        onSuccess(ctx) {
            //
        }
    },
})

错误处理

大多数客户端函数返回一个包含以下属性的响应对象:

  • data:响应数据
  • error:如果发生错误,则包含错误对象

错误对象包含以下属性:

  • message:错误消息(例如:"邮箱或密码无效")
  • status:HTTP 状态码
  • statusText:HTTP 状态文本
auth-client.ts
const { data, error } = await authClient.signIn.email({
    email: "email@email.com",
    password: "password1234"
})
if (error) {
    // 处理错误
}

如果操作接受 fetchOptions 选项,你可以传递 onError 回调来处理错误。

auth-client.ts

await authClient.signIn.email({
    email: "email@email.com",
    password: "password1234",
}, {
    onError(ctx) {
        // 处理错误
    }
})

// 或者
await authClient.signIn.email({
    email: "email@email.com",
    password: "password1234",
    fetchOptions: {
        onError(ctx) {
            // 处理错误
        }
    }
})

useSession 这样的钩子函数在获取会话时如果发生错误,也会返回错误对象。此外,它们还会返回一个 isPending 属性来指示请求是否仍在进行中。

auth-client.ts
const { data, error, isPending } = useSession()
if (error) {
    // 处理错误
}

错误代码

客户端实例包含一个 $ERROR_CODES 对象,其中包含服务器返回的所有错误代码。您可以使用它来处理错误翻译或自定义错误消息。

auth-client.ts
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 registrada",
	},
} 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"));
}

插件

您可以通过插件扩展客户端以添加更多功能。插件可以向客户端添加新函数或修改现有函数。

示例:Magic Link 插件

auth-client.ts
import { createAuthClient } from "better-auth/client"
import { magicLinkClient } from "better-auth/client/plugins"

const authClient = createAuthClient({
    plugins: [
        magicLinkClient()
    ]
})

添加插件后,您可以使用插件提供的新函数。

auth-client.ts
await authClient.signIn.magicLink({
    email: "test@email.com"
})

On this page