콘텐츠로 이동

NestJS Backend 아키텍처 선택: Spring 개발자가 Node.js를 만났을 때

Interactive Diagram

새 탭 ↗

Node.js로 Backend를 구축할 때 Express로 시작했다가 프로젝트가 커지면서 구조 정의에 고민이 생긴다. Spring 기반 Backend 개발에 익숙한 팀이라면 NestJS는 매우 자연스러운 선택이다. 이 글은 NestJS를 Backend Framework로 선택한 배경과 실무에서 적용한 아키텍처 패턴을 다룬다.

Node.js v16.15.x 이상 stable 기준으로 Backend Framework를 검토했을 때, NestJS가 가진 강점은 명확했다.

  • OOP + FP 결합: Spring에서 익숙한 Dependency Injection, Module 분리, Decorator 패턴을 그대로 쓸 수 있다.
  • TypeScript 기본 지원: Pure JavaScript에서 다루기 어려운 타입 안전성과 IDE 지원을 framework 수준에서 제공한다.
  • CLI로 boilerplate 자동 생성: nest generate resource로 REST API의 Controller, Service, DTO, Entity를 한 번에 생성하고 AppModule에 auto-import까지 된다.

NestJS 모듈 구조: Application Module 아래에 Users, Orders, Chat Module이 있고 Orders에 Feature Module 1, 2, Chat에 Feature Module 3이 연결 출처: NestJS 문서, Modules, Kamil Mysliwiec and NestJS contributors, MIT

  • 초기 검토: https://github.com/{organization}/backend-nestjs-poc
  • 기능 검증: https://github.com/{organization}/backend-nestjs-validation
    • ORM: TypeORM, Prisma
    • ODM: Mongoose
    • Redis 기반 Cache, Queue 활용

CLI는 framework 초기 setup과 표준 구조 정의에는 강력하지만, 이미 제공된 framework 내에서 API를 추가할 때는 굳이 사용하지 않아도 관계 없다. 기존 module 구조를 복사해서 수정하는 편이 더 빠를 때도 많다.

Terminal window
npm i -g @nestjs/cli

nest generate resource를 실행하면 REST API + CRUD endpoint가 자동 생성된다.

  • 디렉터리src/
    • 디렉터리users/
      • 디렉터리dto/
        • create-user.dto.ts
        • update-user.dto.ts
      • 디렉터리entities/
        • user.entity.ts
        • user.provider.ts
      • users.controller.ts
      • users.module.ts
      • users.service.ts

module, controller, service, dto, entity가 한 번에 생성되고 AppModule에 자동 import된다.

Generate a Nest element.
Schematics available on @nestjs/schematics collection:
┌───────────────┬─────────────┬──────────────────────────────────────────────┐
│ name │ alias │ description │
│ application │ application │ Generate a new application workspace │
│ class │ cl │ Generate a new class │
│ controller │ co │ Generate a controller declaration │
│ decorator │ d │ Generate a custom decorator │
│ filter │ f │ Generate a filter declaration │
│ gateway │ ga │ Generate a gateway declaration │
│ guard │ gu │ Generate a guard declaration │
│ interceptor │ in │ Generate an interceptor declaration │
│ interface │ interface │ Generate an interface │
│ middleware │ mi │ Generate a middleware declaration │
│ module │ mo │ Generate a module declaration │
│ pipe │ pi │ Generate a pipe declaration │
│ provider │ pr │ Generate a provider declaration │
│ resolver │ r │ Generate a GraphQL resolver declaration │
│ service │ s │ Generate a service declaration │
│ library │ lib │ Generate a new library within a monorepo │
│ sub-app │ app │ Generate a new application within a monorepo │
│ resource │ res │ Generate a new CRUD resource │
└───────────────┴─────────────┴──────────────────────────────────────────────┘

Configuration 분리: 환경별 .env 관리

섹션 제목: “Configuration 분리: 환경별 .env 관리”

NestJS는 @nestjs/config package로 configuration 관리를 framework 수준에서 제공한다. 내부적으로 dotenv를 사용하며 process.env로 접근한다.

  • 디렉터리config/
    • .dev.env
    • .stg.env
    • .prd.env
    • .local.env
Dockerfile
ENV NODE_ENV=dev
app.module.ts
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath:
'config/' +
(process.env.NODE_ENV === 'prd'
? '.prd.env'
: process.env.NODE_ENV === 'stg'
? '.stg.env'
: process.env.NODE_ENV === 'dev'
? '.dev.env'
: '.local.env'),
}),
// ...
],
})
export class AppModule {}

이렇게 하면 container build 시점에 환경이 결정되고, 런타임에 설정을 바꿀 필요가 없다.

Logger 설정: Winston + Access Logging Middleware

섹션 제목: “Logger 설정: Winston + Access Logging Middleware”

NestJS는 @nestjs/common에 내장 logger를 제공하지만, 실무에서는 Winston을 사용하고 Access Logging Middleware를 별도로 구현해서 모든 요청·응답을 구조화된 형태로 기록한다.

LoggerModule과 WinstonMiddleware 적용 (app.module.ts)

섹션 제목: “LoggerModule과 WinstonMiddleware 적용 (app.module.ts)”
app.module.ts
import { LoggerModule, WinstonMiddleware } from 'common-modules';
@Module({
imports: [
LoggerModule,
// ...
],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(WinstonMiddleware).forRoutes('*');
}
}

공통 module은 별도 repository로 분리해서 여러 Backend 프로젝트에서 재사용한다.

Swagger / OpenAPI: 자동 API 문서 생성

섹션 제목: “Swagger / OpenAPI: 자동 API 문서 생성”

NestJS는 Decorator 기반으로 Swagger/OpenAPI 문서를 자동 생성한다. Controller와 DTO에 metadata를 추가하면 API 문서가 실시간으로 갱신된다.

main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
const config = new DocumentBuilder()
.setTitle('Backend API')
.setDescription('Backend REST API documentation')
.setVersion('1.0')
.addTag('users')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

/api 엔드포인트로 접속하면 Swagger UI가 표시되고, 모든 endpoint·DTO·response schema를 확인할 수 있다.

import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({ description: '사용자 이름', example: 'noisonnoiton' })
name: string;
@ApiProperty({ description: '이메일', example: 'user@example.com' })
email: string;
}

이 metadata는 Swagger 문서뿐 아니라 validation decorator로도 사용할 수 있다.

  • CLI 의존도를 낮춰라: CLI는 초기 구조 정의에만 쓰고, 이후에는 수동으로 파일을 복사·수정하는 편이 빠를 때가 많다.
  • 공통 module을 분리하라: Logger, Auth, Config 같은 공통 기능은 별도 package로 분리해서 여러 프로젝트에서 재사용한다.
  • 환경 변수는 container build 시점에 결정하라: 런타임 설정 변경은 위험하고 디버깅이 어렵다.
  • Swagger는 필수다: API 문서가 코드와 항상 sync되므로 별도 문서 관리 비용이 사라진다.

이 아키텍처 위에서 실제 Database 연결을 어떻게 선택했는지는 Node.js ORM 비교: TypeORM, Sequelize, Prisma에서 이어진다. Redis 활용 패턴은 NestJS Redis 패턴에서 다룬다.