Astro 集成

Better Auth 为 Astro 提供一流支持。本指南将向您展示如何将 Better Auth 与 Astro 集成。

在开始之前,请确保您已配置 Better Auth 实例。如果您尚未这样做,请查看 安装

挂载处理程序

要启用 Better Auth 处理请求,我们需要将处理程序挂载到捕获所有 API 路由。在 /pages/api/auth 内创建一个名为 [...all].ts 的文件,并添加以下代码:

pages/api/auth/[...all].ts
import { auth } from "~/auth";
import type { APIRoute } from "astro";

export const ALL: APIRoute = async (ctx) => {
	// If you want to use rate limiting, make sure to set the 'x-forwarded-for' header to the request headers from the context
	// ctx.request.headers.set("x-forwarded-for", ctx.clientAddress);
	return auth.handler(ctx.request);
};

您可以在 better-auth 配置中更改路径,但推荐保持为 /api/auth/[...all]

创建客户端

Astro 支持多种前端框架,因此您可以根据使用的框架轻松导入客户端。

如果您不使用前端框架,您仍然可以导入 vanilla 客户端。

lib/auth-client.ts
import { createAuthClient } from "better-auth/client"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/react"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/vue"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/svelte"
export const authClient =  createAuthClient()
lib/auth-client.ts
import { createAuthClient } from "better-auth/solid"
export const authClient =  createAuthClient()

认证中间件

Astro Locals 类型

要为您的 Astro locals 提供类型,您需要在 env.d.ts 文件中设置它。

env.d.ts

/// <reference path="../.astro/types.d.ts" />

declare namespace App {
    // Note: 'import {} from ""' syntax does not work in .d.ts files.
    interface Locals {
        user: import("better-auth").User | null;
        session: import("better-auth").Session | null;
    }
}

中间件

要保护您的路由,您可以在中间件中使用 getSession 方法检查用户是否已认证,并使用之前设置的类型通过 Astro locals 设置用户和会话数据。从在项目根目录创建 middleware.ts 文件开始,并按照以下示例操作:

middleware.ts
import { auth } from "@/auth";
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware(async (context, next) => {
    const isAuthed = await auth.api
        .getSession({
            headers: context.request.headers,
        })

    if (isAuthed) {
        context.locals.user = isAuthed.user;
        context.locals.session = isAuthed.session;
    } else {
        context.locals.user = null;
        context.locals.session = null;
    }

    return next();
});

.astro 文件中从服务器获取会话

您可以使用 Astro.locals 检查用户是否有会话并从服务器端获取用户数据。以下是在 .astro 文件中获取会话的示例:

---
import { UserCard } from "@/components/user-card";

const session = () => {
    if (Astro.locals.session) {
        return Astro.locals.session;
    } else {
        // Redirect to login page if the user is not authenticated
        return Astro.redirect("/login");
    }
}

---

<UserCard initialSession={session} />

On this page