본문 바로가기
NestJS

[NestJS] Middleware

by Programmer.Junny 2025. 3. 11.

Middleware란?

미들웨어는 HTTP 요청이 컨트롤러에 도달하기 전, 초기 단계에서 요청 전처리를 수행할 수 있는 함수이다. 이는 Express 미들웨어와 매우 유사하게 동작하며, 로깅, 인증, 요청 파싱 등의 다양한 작업을 수행할 수 있다.

Middleware 생성하고 사용해보기

import { Injectable, NestMiddleware } from "@nestjs/common";
import { NextFunction } from "express";

@Injectable()
export class LogMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: NextFunction) {
        console.log(`[REQ] ${req.method} ${req.url} ${new Date().toLocaleString('kr')}`);

        next();
    }
}

Express에서 사용한 미들웨어와 같이 마지막에 next()를 넣어주어야 다음 미들웨어가 실행된다.

import { ClassSerializerInterceptor, MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PostsModule } from './posts/posts.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PostsModel } from './posts/entities/posts.entity';
import { UsersModule } from './users/users.module';
import { UsersModel } from './users/entities/users.entity';
import { AuthModule } from './auth/auth.module';
import { CommonModule } from './common/common.module';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { ENV_DB_DATABASE_KEY, ENV_DB_HOST_KEY, ENV_DB_PASSWORD_KEY, ENV_DB_PORT_KEY, ENV_DB_USERNAME_KEY } from './common/const/env-keys.const';
import { ServeStaticModule } from '@nestjs/serve-static';
import { PUBLIC_FOLDER_PATH } from './common/const/path.const';
import { ImageModel } from './common/entity/image.entity';
import { LogMiddleware } from './common/middleware/log.middleware';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      // xxx.jpg
      // rootPath만 있을 시 -> http://localhost:3000/posts/xxx.jpg
      rootPath: PUBLIC_FOLDER_PATH,
      // serveRoot를 추가 시 -> http://localhost:3000/public/posts/xxx.jpg
      serveRoot: '/public',
    }),
    ConfigModule.forRoot({
      envFilePath: '.env',
      isGlobal: true,
    }),
    PostsModule,
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: process.env[ENV_DB_HOST_KEY],
      port: parseInt(process.env[ENV_DB_PORT_KEY]!),
      username: process.env[ENV_DB_USERNAME_KEY],
      password: process.env[ENV_DB_PASSWORD_KEY],
      database: process.env[ENV_DB_DATABASE_KEY],
      entities: [
        PostsModel,
        UsersModel,
        ImageModel
      ],
      synchronize: true, //프로덕션 환경에선 false해야함
    }),
    UsersModule,
    AuthModule,
    CommonModule,
  ],
  controllers: [AppController],
  providers: [AppService, {
    provide: APP_INTERCEPTOR,
    useClass: ClassSerializerInterceptor,
  }],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(
      LogMiddleware,
    ).forRoutes({
      path: '*',
      method: RequestMethod.ALL,
    });
  }
}
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(
      LogMiddleware,
    ).forRoutes({
      path: '*',
      method: RequestMethod.ALL,
    });
  }
}

미들웨어는 데코레이터(어노테이션)를 사용하지 않고 모듈에서 적용할 수 있다.

위의 코드는 app.module.ts에서 적용하였기 때문에 모든 라우터가 실행될 때 미들웨어가 실행되게 된다.

또한 forRoutes()를 통해 실행될 라우터 경로(API)와 메서드 등을 설정할 수 있다.

'NestJS' 카테고리의 다른 글

[NestJS] SocketIO 심화  (1) 2025.03.12
[NestJS] SocketIO 일반  (0) 2025.03.12
[NestJS] Exception Filter  (0) 2025.03.10
[NestJS] Interceptor  (0) 2025.03.10
[NestJS] Transaction  (0) 2025.03.10

최근댓글

최근글

skin by © 2024 ttuttak