미들웨어는 무엇일까??
- 미들웨어는 Express와 마찬가지로 요청(Request)과 응답(Response) 사이에서 실행되는 함수이다.
- 요청의 전처리(인증, 유효성검사, 로깅) 후 다음 스텝으로 넘겨주는게 필요할때 사용함
- Nest 미들웨어는 의존성 주입(Dependency Injection)을 완벽하게 지원함
미들웨어 생성 - logger.middleware.ts

import { Injectable } from '@nestjs/common';
@Injectable()
export class LoggerMiddleware {
use(req, res, next) {
console.log('Request...');
next();
}
}
middleware 폴더를 하나 생성 후 logger.middleware.ts 파일을 하나 만들어주었다. 그리고 위의 코드와 같이 입력한다. 그리고 이제 루트 모듈로 넘어가서 인터페이스에 대한 구현을 해야하는데 아래의 코드를 보고 똑같이 입력한다.
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { LoggerMiddleware } from './middleware/logger.middleware';
import { UsersModule } from './users/users.module';
@Module({
imports: [UsersModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware);
}
}
- NestModule
- MiddlewareConsumer
위의 3가지를 한번 간단하게 설명을 하고 넘어가도록 하자.
- NestModule
configure(consumer: MiddlewareConsumer) 메서드를 가진 인터페이스
인터페이스를 구현해야 쓸 수 있기 때문에 implements 하여 구현한다. - MiddlewareConsumer
미들웨어를 실제로 바인딩 하기 위한 객체
apply(...).forRoutes(...), exclude(...) 같은 체이닝 API를 제공한다.
위의 코드에는 현재 미들웨어를 생성만 하고 바인딩은 하지 않은 상태이다. 아래의 코드로 수정하여 전체 라우터에 미들웨어를 설정해보자.
consumer.apply(LoggerMiddleware).forRoutes('*');

"localhost:3000/" 경로나 "localhost:3000/users/findUsers" 어느 경로로 접속해도 위와 같이 console.log()가 출력되는걸 볼 수 있다.
함수형 미들웨어
import { Injectable } from '@nestjs/common';
import { NextFunction } from 'express';
//클래스형
@Injectable()
export class LoggerMiddleware {
use(req, res, next) {
console.log('Request...');
next();
}
}
//함수형
export function logger(req: Request, res: Response, next: NextFunction) {
console.log('function Reqeust....');
console.log(req.headers);
next();
}
위의 코드를 보면 logger 함수를 볼 수 있다. 이렇게 만든 후 루트 모듈에 가서 삽입해주면 함수형 미들웨어도 정상작동 된다. 아래의 코드와 같이 수정을 해보자.
consumer.apply(logger).forRoutes('*');

간단하게 미들웨어를 설정해 보았다. 3년 전 Express로 미들웨어를 설정하여 각 경로로 접속하는 세션을 확인하는 코드를 짰던 기억이 났는데, 생각보다 nestjs에서 미들웨어 셋팅이 아주 간단한 느낌을 받았다.
참고
https://docs.nestjs.com/middleware
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea
docs.nestjs.com
https://joonfluence.tistory.com/884
NestJS 완전정복: 미들웨어, 가드, 인터셉터, 파이프의 모든 것
1. 미들웨어(Middleware)1.1. 개념 및 역할미들웨어는 Express와 마찬가지로 요청(Request)과 응답(Response) 사이에서 실행되는 함수입니다. HTTP 요청이 컨트롤러의 핸들러에 도달하기 전에 실행되는 함수
joonfluence.tistory.com
'NestJS > 개념과 구조 정리' 카테고리의 다른 글
| NestJS로 효율적인 백엔드 개발하기 (08) - 파이프 (3) | 2025.12.13 |
|---|---|
| NestJS로 효율적인 백엔드 개발하기 (07) - 예외 필터 (0) | 2025.12.12 |
| NestJS로 효율적인 백엔드 개발하기 (05) - 모듈에 대해 알아보자 (0) | 2025.12.12 |
| NestJS로 효율적인 백엔드 개발하기 (04) - 서비스 사용하기 (0) | 2025.12.11 |
| NestJS로 효율적인 백엔드 개발하기 (03) - 컨트롤러 사용하기 (0) | 2025.12.10 |
