NestJs - Request LifeCycle

#NestJs
Written by Dylan2023년 12월 11일 · 2 min read

NestJs - Request LifeCycle

Request LifeCycle

Nest는 Request LifeCycle라고 하는 순서에 따라 요청을 처리하고 응답을 생성한다. Middleware, Pipes, Guards 및 Interceptors를 사용하면 Global, Controller, Route Handler가 작동할 때 Request LifeCycle 동안 특정 코드가 실행되는 위치를 추적하는 것이 어려울 수 있다. 일반적인 요청은 Middleware를 통해 Guards, Interceptors, Pipes, API의 Interceptors로 이동한다.

Middleware

Nest는 전역적으로 바인딩된 Middleware( ex. app.use()로 바인딩된 Middleware )를 실행한 다음 경로에서 결정되는 모듈 바인딩 Middleware를 실행한다. Middleware는 Express의 Middleware 작동 방식과 유사하게 바인딩된 순서대로 순차적으로 실행된다. 서로 다른 모듈에 바인딩된 Middleware의 경우 루트 모듈에 바인딩된 Middleware가 먼저 실행된 다음 모듈이 imports 배열에 추가된 순서대로 Middleware가 실행된다.

Guards

Guards 실행은 Global Guards로 시작하여 Controller Guards로 진행되고 마지막으로 Route Guards로 진행된다. Middleware와 마찬가지로 Guards는 바인딩된 순서대로 실행된다.

Interceptors

대부분의 Interceptors는 Guards와 동일한 패턴을 따르지만 한 가지가 다르다. Interceptors가 RxJS Observable을 반환하므로 Observable은 처음 들어온 순으로 처리된다. 인바운드 요청은 전역, Controller, Route 수준의 확인을 거치지만 요청의 응답이 Controller, Method handler에서 반환된 후, Route에서 Controller, Global순으로 확인한다. Pipes, Controller 또는 Service에서 발생하는 모든 오류는 Interceptors의 catchError 연산자에서 읽을 수 있다.

Pipes

파이프는 @UsePipes() 매개변수와 관련하여 동일한 FIFO 방식으로 Controller에 대한 표준 전역을 따라 바인딩된 시퀀스를 라우팅한다. 그러나 Routing Param 에서 실행 중인 파이프가 여러 개인 경우 파이프는 첫 번째 매개변수부터 마지막 매개변수의 순서로 실행된다. 이는 Route 및 Controller 파이프에도 적용된다.

Filters

필터는 전역을 우선적으로 처리하지 않는 유일한 구성 요소이다. 필터는 가능한 가장 낮은 수준에서부터 확인한다. 모든 Route에 바인딩된 필터, Controller수준, 마지막으로 전역 수준 필터로 진행된다. 예외는 필터에서 필터로 전달될 수 없다. Route 수준 필터가 예외를 포착하는 경우, Controller 또는 전역 수준 필터는 동일한 예외를 포착할 수 없다. 필터에서 필터로 예외를 전달하는 것과 동일한 효과를 내는 방법은 필터 간에 상속을 사용하는 것이다.

Request LifeCycle - 1 사이클

  1. Incoming request
  2. Middleware
    • 2.1. Globally bound middleware
    • 2.2. Module bound middleware
  3. Guards
    • 3.1 Global guards
    • 3.2 Controller guards
    • 3.3 Route guards
  4. Interceptors (pre-controller)
    • 4.1 Global interceptors
    • 4.2 Controller interceptors
    • 4.3 Route interceptors
  5. Pipes
    • 5.1 Global pipes
    • 5.2 Controller pipes
    • 5.3 Route pipes
    • 5.4 Route parameter pipes
  6. Controller (method handler)
  7. Service (if exists)
  8. Interceptors (post-request)
    • 8.1 Route interceptor
    • 8.2 Controller interceptor
    • 8.3 Global interceptor
  9. Exception filters
    • 9.1 route
    • 9.2 controller
    • 9.3 global
  10. Server response

Copyright ⓒ 2026 Dylan All rights reserved.

Created by @Dylan. Powered By @Vallista-land