NestJS 集成

将 Better Auth 与 NestJS 集成。

本指南将向您展示如何将 Better Auth 与 NestJS 集成。

在开始之前,确保您已经配置了一个 Better Auth 实例。如果还没有,请查看安装。

NestJS 集成是社区维护的。如果您遇到任何问题,请在 nestjs-better-auth 提出问题。

安装

安装 NestJS 集成库:

npm install @thallesp/nestjs-better-auth

基本设置

目前该库对 Fastify 的支持处于测试阶段,如果遇到任何问题,请在 nestjs-better-auth 提交问题。

1. 禁用 Body Parser

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

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

在根模块中导入 AuthModule:

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. 路由保护

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

使用 Session 装饰器访问用户会话:

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 仓库。