NestJS Backend 아키텍처 선택: Spring 개발자가 Node.js를 만났을 때
Node.js로 Backend를 구축할 때 Express로 시작했다가 프로젝트가 커지면서 구조 정의에 고민이 생긴다. Spring 기반 Backend 개발에 익숙한 팀이라면 NestJS는 매우 자연스러운 선택이다. 이 글은 NestJS를 Backend Framework로 선택한 배경과 실무에서 적용한 아키텍처 패턴을 다룬다.
왜 NestJS인가
섹션 제목: “왜 NestJS인가”Node.js v16.15.x 이상 stable 기준으로 Backend Framework를 검토했을 때, NestJS가 가진 강점은 명확했다.
Spring과 닮은 구조
섹션 제목: “Spring과 닮은 구조”- 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까지 된다.

실제 프로젝트 Repository
섹션 제목: “실제 프로젝트 Repository”- 초기 검토:
https://github.com/{organization}/backend-nestjs-poc - 기능 검증:
https://github.com/{organization}/backend-nestjs-validation- ORM: TypeORM, Prisma
- ODM: Mongoose
- Redis 기반 Cache, Queue 활용
NestJS CLI 활용: 필요할 때만
섹션 제목: “NestJS CLI 활용: 필요할 때만”CLI는 framework 초기 setup과 표준 구조 정의에는 강력하지만, 이미 제공된 framework 내에서 API를 추가할 때는 굳이 사용하지 않아도 관계 없다. 기존 module 구조를 복사해서 수정하는 편이 더 빠를 때도 많다.
CLI 설치
섹션 제목: “CLI 설치”npm i -g @nestjs/cliResource 자동 생성
섹션 제목: “Resource 자동 생성”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된다.
생성 가능한 element 목록
섹션 제목: “생성 가능한 element 목록”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 파일
섹션 제목: “환경별 config 파일”디렉터리config/
- .dev.env
- .stg.env
- .prd.env
- .local.env
Dockerfile에서 환경 변수 설정
섹션 제목: “Dockerfile에서 환경 변수 설정”ENV NODE_ENV=devConfigModule import (app.module.ts)
섹션 제목: “ConfigModule import (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)”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 문서가 실시간으로 갱신된다.
Swagger 설정 (main.ts)
섹션 제목: “Swagger 설정 (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를 확인할 수 있다.
DTO에 Swagger metadata 추가
섹션 제목: “DTO에 Swagger metadata 추가”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 패턴에서 다룬다.