# NestJS 集成 (/docs/integrations/nestjs)

将 Better Auth 与 NestJS 集成。



本指南将向您展示如何将 Better Auth 与 [NestJS](https://nestjs.com/) 集成。

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

<Callout type="info">
  NestJS 集成是**社区维护**的。如果您遇到任何问题，请在 [nestjs-better-auth](https://github.com/ThallesP/nestjs-better-auth) 提出问题。
</Callout>

## 安装 [#安装]

安装 NestJS 集成库：

<CodeBlockTabs defaultValue="npm" groupId="persist-install">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="npm">
      npm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="pnpm">
      pnpm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="yarn">
      yarn
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="bun">
      bun
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="npm">
    ```bash
    npm install @thallesp/nestjs-better-auth
    ```
  </CodeBlockTab>

  <CodeBlockTab value="pnpm">
    ```bash
    pnpm add @thallesp/nestjs-better-auth
    ```
  </CodeBlockTab>

  <CodeBlockTab value="yarn">
    ```bash
    yarn add @thallesp/nestjs-better-auth
    ```
  </CodeBlockTab>

  <CodeBlockTab value="bun">
    ```bash
    bun add @thallesp/nestjs-better-auth
    ```
  </CodeBlockTab>
</CodeBlockTabs>

## 基本设置 [#基本设置]

<Callout type="warn">
  目前该库对 Fastify 的支持处于**测试阶段**，如果遇到任何问题，请在 [nestjs-better-auth](https://github.com/thallesp/nestjs-better-auth) 提交问题。
</Callout>

### 1. 禁用 Body Parser [#1-禁用-body-parser]

禁用 NestJS 内置的 body parser，以允许 Better Auth 处理原始请求体：

```ts title="main.ts"
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bodyParser: false, // Better Auth 需要
  });
  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
```

### 2. 导入 AuthModule [#2-导入-authmodule]

在根模块中导入 `AuthModule`：

```ts title="app.module.ts"
import { Module } from '@nestjs/common';
import { AuthModule } from '@thallesp/nestjs-better-auth';
import { auth } from "./auth"; // 您的 Better Auth 实例

@Module({
  imports: [
    AuthModule.forRoot({ auth }),
  ],
})
export class AppModule {}
```

### 3. 路由保护 [#3-路由保护]

**默认全局保护**：该模块会全局注册一个 `AuthGuard`。所有路由默认受到保护，除非您显式允许访问。

使用 `Session` 装饰器访问用户会话：

```ts title="user.controller.ts"
import { Controller, Get } from '@nestjs/common';
import { Session, UserSession, AllowAnonymous, OptionalAuth } from '@thallesp/nestjs-better-auth';

@Controller('users')
export class UserController {
  @Get('me')
  async getProfile(@Session() session: UserSession) {
    return { user: session.user };
  }

  @Get('public')
  @AllowAnonymous() // 允许匿名访问
  async getPublic() {
    return { message: '公共路由' };
  }

  @Get('optional')
  @OptionalAuth() // 认证可选
  async getOptional(@Session() session: UserSession) {
    return { authenticated: !!session };
  }
}
```

## 完整文档 [#完整文档]

有关装饰器、钩子、全局守卫和高级配置的完整文档，请访问 [NestJS Better Auth 仓库](https://github.com/thallesp/nestjs-better-auth)。

