Trung BìnhNestJS iconNestJS

Giải thích Request Lifecycle trong NestJS: Middleware → Guards → Interceptors → Pipes → Controller → Exception Filters.

NestJS xử lý request qua pipeline theo thứ tự cố định: Middleware chạy đầu tiên (logging, CORS, session — access raw req/res), tiếp theo Guards kiểm tra authorization (trả về true/false), rồi Interceptors pre-processing (transform request trước khi vào handler), sau đó Pipes validate và transform input data, tiếp theo Controller Handler thực thi business logic chính, rồi Interceptors post-processing (transform response), cuối cùng Exception Filters bắt và format errors thành response chuẩn.

Middleware và Guards đều chạy trước handler nhưng Guards có access vào ExecutionContext nên biết handler nào sẽ được gọi. Exception Filters chỉ hoạt động khi có exception, nếu không có lỗi thì bỏ qua. Mỗi layer có thể áp dụng theo thứ tự: global → controller → route.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS