NestJS 集成
本指南将向您展示如何将 Better Auth 与 NestJS 集成。
在开始之前,请确保您已配置 Better Auth 实例。如果您尚未完成,请查看 安装。
NestJS 集成由社区维护。如果您遇到任何问题,请在 nestjs-better-auth 打开问题。
安装
安装 NestJS 集成库:
npm install @thallesp/nestjs-better-auth基本设置
当前,Better Auth 的 NestJS 集成仅支持 Express,不支持 Fastify。
1. 禁用 Body Parser
禁用 NestJS 内置的 body parser 以允许 Better Auth 处理原始请求体:
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:
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 来保护您的路由:
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard, Session, UserSession } from '@thallesp/nestjs-better-auth';
@Controller('users')
@UseGuards(AuthGuard)
export class UserController {
@Get('me')
async getProfile(@Session() session: UserSession) {
return { user: session.user };
}
}完整文档
有关包括装饰器、钩子、全局守卫和高级配置的完整文档,请访问 NestJS Better Auth 仓库。