Astro 集成

Better Auth 提供针对 Astro 的一流支持。本指南将向你展示如何将 Better Auth 与 Astro 集成。

【Better Auth comes with first class support for Astro. This guide will show you how to integrate Better Auth with Astro.】

在开始之前,请确保你已配置了 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.】

安装处理程序

【Mount the handler】

为了使 Better Auth 能够处理请求,我们需要将处理程序挂载到一个通用 API 路由上。在 /pages/api/auth 目录下创建一个名为 [...all].ts 的文件,并添加以下代码:

【To enable Better Auth to handle requests, we need to mount the handler to a catch all API route. Create a file inside /pages/api/auth called [...all].ts and add the following code:】

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]

创建客户端

【Create a client】

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

【Astro supports multiple frontend frameworks, so you can easily import your client based on the framework you're using.】

如果你没有使用前端框架,你仍然可以导入原生客户端。

【If you're not using a frontend framework, you can still import the vanilla client.】

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()

身份验证中间件

【Auth Middleware】

天文本地类型

【Astro Locals types】

要为你的 Astro 本地变量设置类型,你需要在 env.d.ts 文件中进行设置。

【To have types for your Astro locals, you need to set it inside the env.d.ts file.】

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;
    }
}

中间件

【Middleware】

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

【To protect your routes, you can check if the user is authenticated using the getSession method in middleware and set the user and session data using the Astro locals with the types we set before. Start by creating a middleware.ts file in the root of your project and follow the example below:】

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 文件中获取服务器上的会话

【Getting session on the server inside .astro file】

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

【You can use Astro.locals to check if the user has session and get the user data from the server side. Here is an example of how you can get the session inside an .astro file:】

---
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