NestJS 集成
本指南将向你展示如何将 Better Auth 与 NestJS 集成。
【This guide will show you how to integrate Better Auth with NestJS.】
在开始之前,请确保你已配置了 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.】
NestJS 集成是 社区维护 的。如果你遇到任何问题,请在 nestjs-better-auth 提交。
安装
【Installation】
安装 NestJS 集成库:
【Install the NestJS integration library:】
npm install @thallesp/nestjs-better-auth基本设置
【Basic Setup】
目前该库对 Fastify 提供了 Beta 支持,如果你在使用中遇到任何问题,请在 nestjs-better-auth 上提交问题。
1. 禁用 Body Parser
【1. Disable Body Parser】
禁用 NestJS 内置的 body 解析器,以便 Better Auth 可以处理原始请求体:
【Disable NestJS's built-in body parser to allow Better Auth to handle the raw request body:】
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
bodyParser: false, // Required for Better Auth
});
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();2. 导入 AuthModule
【2. Import AuthModule】
在你的根模块中导入 AuthModule:
【Import the AuthModule in your root module:】
import { Module } from '@nestjs/common';
import { AuthModule } from '@thallesp/nestjs-better-auth';
import { auth } from "./auth"; // Your Better Auth instance
@Module({
imports: [
AuthModule.forRoot({ auth }),
],
})
export class AppModule {}3. 路由保护
【3. Route Protection】
默认全局:该模块全局注册了一个 AuthGuard。所有路由都受保护,除非你明确允许访问。
使用 Session 装饰器来访问用户会话:
【Use the Session decorator to access the user session:】
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() // Allow anonymous access
async getPublic() {
return { message: 'Public route' };
}
@Get('optional')
@OptionalAuth() // Authentication is optional
async getOptional(@Session() session: UserSession) {
return { authenticated: !!session };
}
}完整文档
【Full Documentation】
有关完整文档,包括装饰器、钩子、全局守卫和高级配置,请访问 NestJS Better Auth 仓库。
【For comprehensive documentation including decorators, hooks, global guards, and advanced configuration, visit the NestJS Better Auth repository.】