본문으로 건너뛰기
김신건의 로그

[Framework] NestJS

· 수정 · 📖 약 3분 · 927자/단어 #nestjs #nodejs #typescript #framework #backend
NestJS, Nest.js, nestjs, Nest framework, nest framework, TypeScript NestJS, Node NestJS, NestJS 11

정의

NestJS 는 Kamil Myśliwiec 이 2017년 발표한 Node.js 서버측 프레임워크 입니다. TypeScript first, Angular 에서 영감받은 모듈 + DI + 데코레이터 아키텍처. Express (기본) 또는 Fastify 를 HTTP 어댑터로 사용하며, REST/GraphQL/WebSocket/gRPC/Microservice 를 하나의 프로그래밍 모델로 커버합니다.

2025년 현재 NestJS 11 이 stable (Node 20 minimum, better logging, microservices status, etc).

왜 NestJS 인가

1. TypeScript 그대로

TypeScript 를 처음부터 상정. 데코레이터, 타입 추론, IDE 지원 최상급.

2. 예측 가능한 구조

Angular 스타일. 새 팀원이 어디에 무엇이 있는지 즉시 파악.

  • Module: 기능 그룹
  • Controller: HTTP 라우트
  • Service (Provider): 비즈니스 로직
  • DTO / Schema: 데이터 전송 객체
  • Guard / Interceptor / Pipe / Filter: 요청 lifecycle 훅

3. Dependency Injection

Class-based DI. Constructor injection. 테스트 편의성 극대화.

4. 방대한 통합

TypeORM, Prisma, Mongoose, GraphQL (Apollo), Swagger, Passport, Bull, Kafka, gRPC, Redis, Elasticsearch, WebSocket, SSE.

5. Microservice

같은 코드로 REST + Microservice (Kafka, NATS, RabbitMQ, TCP, gRPC).

빠른 시작

npm i -g @nestjs/cli
nest new myapp
cd myapp
npm run start:dev

기본 구조:

myapp/
├── src/
│   ├── main.ts          # 진입점 (bootstrap)
│   ├── app.module.ts    # root module
│   ├── app.controller.ts
│   └── app.service.ts
├── test/
│   └── app.e2e-spec.ts
├── tsconfig.json
├── nest-cli.json
└── package.json

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);
}
bootstrap();

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

아키텍처 요약

flowchart LR
  R[HTTP Request] --> MW[Middleware]
  MW --> G[Guard]
  G --> IC1[Interceptor pre]
  IC1 --> P[Pipe]
  P --> C[Controller]
  C --> S[Service<br/>Provider]
  S --> DB[(DB / External)]
  S --> C
  C --> IC2[Interceptor post]
  IC2 --> F[Exception Filter]
  F --> Resp[HTTP Response]

핵심 개념

개념역할자세히
**[[nestjs-modulesModule]]**기능 그룹, DI scope
**[[nestjs-controllersController]]**HTTP 라우팅
**[[nestjs-providersProvider]]**Injectable class (Service, Repository, Factory)
**[[nestjs-guardsGuard]]**인증/인가
**[[nestjs-interceptorsInterceptor]]**Cross-cutting (logging, cache, transform)
**[[nestjs-pipesPipe]]**검증, 변환
**[[nestjs-middlewareMiddleware]]**Express-style middleware
**[[nestjs-exception-filtersException Filter]]**예외 처리

Request Lifecycle 순서

  1. Middleware: Express/Fastify 미들웨어. req 만 접근.
  2. Guard: canActivate(context). false 면 즉시 401/403.
  3. Interceptor (before): intercept(context, next) 상반부.
  4. Pipe: 파라미터 검증/변환 (DTO 로 형변환).
  5. Controller method: 실제 라우트 핸들러.
  6. Interceptor (after): map(...) 로 응답 변환.
  7. Exception filter: 어떤 계층이든 예외 발생 시.

HTTP Adapter

  • Express (@nestjs/platform-express, 기본): Express 4/5 호환
  • Fastify (@nestjs/platform-fastify): 더 빠름, TypeBox / AJV 스키마
const app = await NestFactory.create<NestFastifyApplication>(
  AppModule,
  new FastifyAdapter(),
);

Interface 만 다르고 대부분의 NestJS 코드는 그대로.

DTO + Validation

import { IsEmail, IsInt, Min } from 'class-validator';

export class CreateUserDto {
  @IsEmail()
  email: string;

  @IsInt()
  @Min(18)
  age: number;
}
@Post()
create(@Body() dto: CreateUserDto) {
  // dto 는 이미 validated + typed
}

ValidationPipe 를 global 로 등록하면 모든 DTO 자동 검증. 자세한 것은 Pipes 참조.

Swagger / OpenAPI

npm i @nestjs/swagger swagger-ui-express
// main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

const config = new DocumentBuilder()
  .setTitle('My API')
  .setDescription('...')
  .setVersion('1.0')
  .addBearerAuth()
  .build();

const doc = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, doc);

@ApiProperty() 데코레이터로 DTO 문서화. http://localhost:3000/api 에 Swagger UI.

CLI

nest g mo users         # module
nest g co users         # controller
nest g s users          # service
nest g res users        # resource (module + controller + service + DTO + entity)

nest g guard auth
nest g interceptor logging
nest g pipe validate
nest g filter http-exception

nest build
nest start --watch

NestJS 11 주요 변경

  • Node 20 minimum: Node 18 EOL
  • JSON Logger: nest.useLogger(new ConsoleLogger({ json: true }))
  • 개선된 Logger: 더 나은 formatting, maps/sets 지원
  • Microservices: status(), unwrap(), on() 메서드 (transporter 상태)
  • NATS: queue-per-handler 지원
  • WebDAV HTTP method 지원
  • @Inject() type narrowing: TypeScript 개선
  • ParseDatePipe: 새 pipe
  • plainToClass deprecated -> plainToInstance

프로젝트 구조 (실전)

src/
├── main.ts
├── app.module.ts
├── config/
│   ├── database.config.ts
│   ├── app.config.ts
│   └── validation.schema.ts
├── common/
│   ├── decorators/
│   ├── filters/
│   ├── guards/
│   ├── interceptors/
│   ├── pipes/
│   └── middleware/
├── modules/
│   ├── users/
│   │   ├── users.module.ts
│   │   ├── users.controller.ts
│   │   ├── users.service.ts
│   │   ├── users.repository.ts    # 또는 Prisma/TypeORM
│   │   ├── dto/
│   │   │   ├── create-user.dto.ts
│   │   │   └── update-user.dto.ts
│   │   ├── entities/
│   │   │   └── user.entity.ts
│   │   └── users.controller.spec.ts
│   ├── auth/
│   │   ├── auth.module.ts
│   │   ├── strategies/
│   │   └── guards/
│   └── health/
└── shared/

실전 조합 (스택)

카테고리관용 선택
HTTPFastify (성능) 또는 Express
DBPrisma (모던) 또는 TypeORM (성숙) 또는 Drizzle
인증Passport + JWT, 또는 자체 JWT strategy
Validationclass-validator + class-transformer, 또는 Zod
Config@nestjs/config + Joi schema
LoggingPino (nestjs-pino) 또는 built-in JSON logger
TestingJest (내장) + Supertest
Task QueueBull / BullMQ (@nestjs/bull)
CacheRedis (@nestjs/cache-manager)
Docs@nestjs/swagger
MonitoringOpenTelemetry (@opentelemetry/instrumentation-nestjs-core)

함정

WARNING

DI 순환 참조. Module A imports B, B imports A. forwardRef(() => ModuleB) 로 해결하지만 근본 refactoring 이 나음.

CAUTION

Global module 남용. @Global() 는 어디서든 provider 접근 가능. 편해 보이지만 의존성 추적 어려움.

WARNING

class-validator 는 런타임 필요. Nest 는 TypeScript 를 컴파일하고 나서도 metadata 필요. reflect-metadata import 필수 (main.ts 상단).

IMPORTANT

Fastify 는 Express 미들웨어와 호환 X. 이관 시 미들웨어/plugin 재작성.

CAUTION

useFactory DI 는 async 가능. 하지만 초기화 순서 이해 필요. Circular deps 조심.

관련 위키

이 글의 용어 (17개)
[Framework] Koa.jsframeworks
정의 Koa.js 는 Express 창시자 TJ Holowaychuk 이 2013년 발표한 Node.js 웹 프레임워크 입니다. Express 의 후계자 성격이며, 미들웨어를 a…
[NestJS] Config (Environment, Validation)frameworks
정의 NestJS Config 는 패키지로 환경변수를 관리합니다. 파일 로딩, TypeScript type-safe access, 검증 (Joi/Zod), 여러 환경 (dev/s…
[NestJS] Controllersframeworks
정의 NestJS Controller 는 데코레이터가 붙은 클래스로, HTTP 요청을 라우팅하고 응답을 반환합니다. Method 별로 , , , , 데코레이터를 붙여 URL + …
[NestJS] Database (TypeORM, Prisma, Mongoose, Drizzle)frameworks
정의 NestJS Database 통합은 여러 ORM/ODM 을 module 로 감싸 DI + 트랜잭션 + 마이그레이션을 관용화합니다. 주요 선택지: TypeORM (성숙), P…
[NestJS] Deployment (Docker, Kubernetes, PM2)frameworks
정의 NestJS Deployment 는 프로덕션 환경에서 앱을 배포/운영하기 위한 절차입니다. Docker 이미지 빌드, Kubernetes 매니페스트, PM2 프로세스 관리,…
[NestJS] Exception Filtersframeworks
정의 NestJS Exception Filter 는 애플리케이션에서 발생한 예외를 catch 하여 클라이언트에게 응답 형식을 통일합니다. 데코레이터로 어떤 예외를 처리할지 지정합…
[NestJS] Guardsframeworks
정의 NestJS Guard 는 특정 요청이 controller method 에 도달하기 전에 실행되어 접근 허용 여부 를 결정합니다. Middleware 이후, Intercep…
[NestJS] Interceptorsframeworks
정의 NestJS Interceptor 는 요청 처리 전/후에 로직을 삽입하는 클래스입니다. AOP (Aspect-Oriented Programming) 패턴의 구현체로, 로깅,…
[NestJS] Microservices (Kafka, NATS, RabbitMQ, gRPC, TCP)frameworks
정의 NestJS Microservices 는 HTTP 대신 message broker (Kafka, RabbitMQ, NATS, Redis) 나 gRPC / TCP 로 통신하는…
[NestJS] Middlewareframeworks
정의 NestJS Middleware 는 route handler 실행 이전, Guard 도 실행되기 전에 실행되는 함수/클래스입니다. Express/Fastify 표준 midd…
[NestJS] Modulesframeworks
정의 NestJS Module 은 데코레이터가 붙은 클래스로, 관련된 controller, provider, import/export 를 하나로 묶는 조직 단위입니다. Angul…
[NestJS] Pipes (Validation, Transformation)frameworks
정의 NestJS Pipe 는 controller method 로 들어가는 인자를 변환 (transformation) 하거나 검증 (validation) 하는 클래스입니다. Gu…
[NestJS] Providers & Dependency Injectionframeworks
정의 NestJS Provider 는 데코레이터가 붙은 클래스 (또는 값/factory) 로, DI container 에 등록되어 다른 클래스에 주입됩니다. Service, Re…
[NestJS] Testing (Jest, Supertest, e2e)frameworks
정의 NestJS Testing 은 Jest (기본) + Supertest 조합으로 unit test 와 e2e test 를 지원합니다. 의 로 module 을 격리된 형태로 만…
[Python] FastAPIfastapi
정의 FastAPI 는 Python 3.8+ 을 위한 ASGI 기반 현대 웹/API 프레임워크 입니다. Sebastián Ramírez (tiangolo) 가 2018년 발표했고…
[TypeScript] Decoratorstypescript
정의 Decorator 는 class, method, accessor, property, parameter 에 부착되는 함수로 그 대상을 검사/수정할 수 있습니다. TypeScr…
TypeScripttypescript
정의 TypeScript 는 Microsoft 가 2012년 발표한 JavaScript 의 상위 집합 프로그래밍 언어입니다. 정적 타입 시스템, 인터페이스, 제네릭, enum, …

💬 댓글

사이트 검색 / 명령어

검색

스크롤 = 확대/축소 · 드래그 = 이동 · 0 = 원래 크기 · ESC = 닫기