Nuxt 集成

在开始之前,请确保你已配置了 Better Auth 实例。如果还没有配置,请查看安装指南

🌐 Before you start, make sure you have a Better Auth instance configured. If you haven't done that yet, check out the installation.

创建 API 路由

🌐 Create API Route

我们需要将处理程序挂载到 API 路由。在 /server/api/auth 目录下创建一个名为 [...all].ts 的文件,并添加以下代码:

🌐 We need to mount the handler to an API route. Create a file inside /server/api/auth called [...all].ts and add the following code:

server/api/auth/[...all].ts
import { auth } from "~/lib/auth"; // import your auth config

export default defineEventHandler((event) => {
	return auth.handler(toWebRequest(event));
});

You can change the path on your better-auth configuration but it's recommended to keep it as /api/auth/[...all]

迁移数据库

🌐 Migrate the database

运行以下命令以在数据库中创建所需的表:

🌐 Run the following command to create the necessary tables in your database:

npx @better-auth/cli migrate

创建客户端

🌐 Create a client

创建一个客户端实例。你可以随意命名文件。在这里,我们在 lib/ 目录下创建 client.ts 文件。

🌐 Create a client instance. You can name the file anything you want. Here we are creating client.ts file inside the lib/ directory.

auth-client.ts
import { createAuthClient } from "better-auth/vue" // make sure to import from better-auth/vue

export const authClient = createAuthClient({
    //you can pass client configuration here
})

一旦创建了客户端,你就可以使用它来注册、登录以及执行其他操作。有些操作是响应式的。

🌐 Once you have created the client, you can use it to sign up, sign in, and perform other actions. Some of the actions are reactive.

示例用法

🌐 Example usage

index.vue
<script setup lang="ts">
import { authClient } from "~/lib/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>

服务器使用

🌐 Server Usage

从 auth 实例导出的 api 对象包含了你可以在服务器上执行的所有操作。在 Better Auth 中创建的每个端点都可以作为函数调用,包括插件端点。

🌐 The api object exported from the auth instance contains all the actions that you can perform on the server. Every endpoint made inside Better Auth is a invocable as a function. Including plugins endpoints.

示例:在服务器 API 路由上获取会话

server/api/example.ts
import { auth } from "~/lib/auth";

export default defineEventHandler((event) => {
    const session = await auth.api.getSession({
      headers: event.headers
    });

   if(session) {
     // access the session.session && session.user
   }
});

SSR 使用

🌐 SSR Usage

如果你在使用带有 SSR 的 Nuxt,你可以在页面组件的 setup 函数中使用 useSession 函数,并传入 useFetch 以使其在 SSR 下工作。

🌐 If you are using Nuxt with SSR, you can use the useSession function in the setup function of your page component and pass useFetch to make it work with SSR.

index.vue
<script setup lang="ts">
import { authClient } from "~/lib/auth-client";

const { data: session } = await authClient.useSession(useFetch);
</script>

<template>
    <p>
        {{ session }}
    </p>
</template>

中间件

🌐 Middleware

要在你的 Nuxt 项目中添加中间件,你可以使用客户端的 useSession 方法。

🌐 To add middleware to your Nuxt project, you can use the useSession method from the client.

middleware/auth.global.ts
import { authClient } from "~/lib/auth-client";
export default defineNuxtRouteMiddleware(async (to, from) => {
	const { data: session } = await authClient.useSession(useFetch); 
	if (!session.value) {
		if (to.path === "/dashboard") {
			return navigateTo("/");
		}
	}
});

资源与示例

🌐 Resources & Examples

On this page