# Astro 集成 (/docs/integrations/astro)

将 Better Auth 集成到 Astro 中。



Better Auth 原生支持 Astro。本指南将向你展示如何将 Better Auth 集成到 Astro 中。

在开始之前，请确保你已经配置了 Better Auth 实例。如果还没有，请查看[安装指南](/docs/installation)。

### 挂载处理器 [#挂载处理器]

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

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

export const ALL: APIRoute = async (ctx) => {
	// 如果你想启用限流，请确保在上下文请求头中设置了 'x-forwarded-for' 头部
	// ctx.request.headers.set("x-forwarded-for", ctx.clientAddress);
	return auth.handler(ctx.request);
};
```

<Callout>
  你可以更改 better-auth 配置中的路径，但建议保持为 `/api/auth/[...all]`
</Callout>

## 创建客户端 [#创建客户端]

Astro 支持多种前端框架，因此你可以根据所使用的框架方便地导入客户端。

<Tabs
  items="[ &#x22;vanilla&#x22;, &#x22;react&#x22;, &#x22;vue&#x22;, &#x22;svelte&#x22;, &#x22;solid&#x22;,
]"
  defaultValue="react"
>
  <Tab value="vanilla">
    ```ts title="lib/auth-client.ts"
    import { createAuthClient } from "better-auth/client"
    export const authClient =  createAuthClient()
    ```
  </Tab>

  <Tab value="react" title="lib/auth-client.ts">
    ```ts title="lib/auth-client.ts"
    import { createAuthClient } from "better-auth/react"
    export const authClient =  createAuthClient()
    ```
  </Tab>

  <Tab value="vue" title="lib/auth-client.ts">
    ```ts title="lib/auth-client.ts"
    import { createAuthClient } from "better-auth/vue"
    export const authClient =  createAuthClient()
    ```
  </Tab>

  <Tab value="svelte" title="lib/auth-client.ts">
    ```ts title="lib/auth-client.ts"
    import { createAuthClient } from "better-auth/svelte"
    export const authClient =  createAuthClient()
    ```
  </Tab>

  <Tab value="solid" title="lib/auth-client.ts">
    ```ts title="lib/auth-client.ts"
    import { createAuthClient } from "better-auth/solid"
    export const authClient =  createAuthClient()
    ```
  </Tab>
</Tabs>

## 认证中间件 [#认证中间件]

### Astro Locals 类型 [#astro-locals-类型]

为了使你的 Astro locals 有类型定义，需要在 `env.d.ts` 文件中进行设置。

```ts title="env.d.ts"

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

declare namespace App {
    // 注意：.d.ts 文件中不支持 'import {} from ""' 语法。
    interface Locals {
        user: import("better-auth").User | null;
        session: import("better-auth").Session | null;
    }
}
```

### 中间件 [#中间件]

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

```ts title="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-文件中服务器端获取会话]

你可以使用 `Astro.locals` 在服务器端检查用户是否有会话，并获取用户数据。下面是一个在 `.astro` 文件内获取会话的示例：

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

const session = () => {
    if (Astro.locals.session) {
        return Astro.locals.session;
    } else {
        // 如果用户未认证，则重定向到登录页
        return Astro.redirect("/login");
    }
}

---

<UserCard initialSession={session} />
```

