NestJS 통합
이 가이드는 Better Auth를 NestJS와 통합하는 방법을 보여줍니다.
시작하기 전에, Better Auth 인스턴스가 설정되어 있는지 확인하세요. 아직 설정하지 않았다면 설치를 확인하세요.
NestJS 통합은 커뮤니티에서 유지 관리합니다. 문제가 발생하면 nestjs-better-auth에서 이슈를 열어주세요.
설치
NestJS 통합 라이브러리를 설치하세요:
npm install @thallesp/nestjs-better-auth기본 설정
현재 라이브러리는 Fastify에 대한 베타 지원을 제공합니다. 문제가 발생하면 nestjs-better-auth에서 이슈를 열어주세요.
1. Body Parser 비활성화
Better Auth가 원시 요청 본문을 처리할 수 있도록 NestJS의 내장 body parser를 비활성화하세요:
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가 전역으로 등록됩니다. 명시적으로 접근을 허용하지 않는 한 모든 라우트가 보호됩니다.
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() // 익명 접근 허용
async getPublic() {
return { message: 'Public route' };
}
@Get('optional')
@OptionalAuth() // 인증은 선택 사항
async getOptional(@Session() session: UserSession) {
return { authenticated: !!session };
}
}전체 문서
데코레이터, 훅, 전역 가드 및 고급 구성을 포함한 포괄적인 문서는 NestJS Better Auth 저장소를 방문하세요.