Client

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

Installation

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

npm i better-auth

Create Client Instance

从您的框架对应的包中导入 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
})

Usage

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

Example: Sign In

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

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

Hooks

除了标准方法外,客户端还提供钩子来轻松访问不同的响应式数据。每个钩子都可在客户端的根对象中访问,并且它们都以 use 开头。

Example: useSession

user.tsx
//确保您使用的是 React 客户端
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 (
        //...
    )
}
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'
        })">
            Continue with GitHub
        </button>
        <div>
            <pre>{{ session.data }}</pre>
            <button v-if="session.data" @click="authClient.signOut()">
                Sign out
            </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
            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>
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}>Log in</button>}
        >
            <button onClick={toggle}>Log out</button>
        </Show>
    ); 
}

Fetch Options

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

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

您可以通过向 createAuthClient 传递 fetchOptions 对象,将任何默认的 fetch 选项传递给客户端。

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

const authClient = createAuthClient({
    fetchOptions: {
        //any better-fetch options
    },
})

您也可以将 fetch 选项传递给大多数客户端函数。作为第二个参数或作为对象中的属性。

auth-client.ts
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) {
            //      
        }
    },
})

Handling Errors

大多数客户端函数返回一个响应对象,该对象具有以下属性:

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

错误对象包含以下属性:

  • message: 错误消息。(例如,“Invalid email or password”)
  • status: HTTP 状态码。
  • statusText: HTTP 状态文本。
auth-client.ts
const { data, error } = await authClient.signIn.email({
    email: "email@email.com",
    password: "password1234"
})
if (error) {
    //handle error
}

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

auth-client.ts

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 这样的钩子如果获取会话时发生错误,也会返回一个错误对象。除此之外,它们还会返回一个 isPending 属性,以指示请求是否仍在挂起。

auth-client.ts
const { data, error, isPending } = useSession()
if (error) {
    //handle error
}

Error Codes

客户端实例包含 $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"));
}

Plugins

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

Example: Magic Link Plugin

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