What is the NestJS Interceptor execution order and how do multiple interceptors interact?
Answer
When multiple interceptors are applied, they execute in a stack-based order. For @UseInterceptors(A, B, C), the pre-handler code runs as A → B → C, and the post-handler (after next.handle()) runs as C → B → A. This mirrors how Express middleware nesting works. Global interceptors run before controller-level, which run before method-level. The RxJS observable chain means each interceptor wraps the next: A.intercept(ctx, { handle: () => B.intercept(ctx, { handle: () => C.intercept(ctx, handler) }) }). Practical implication: if interceptor A handles errors (catchError operator), it catches errors from B, C, and the handler. If B has a timeout, it times out C and the handler. Understanding this nesting is critical when composing logging, caching, timeout, and error-handling interceptors.
More NestJS Questions
View all →- Advanced What is the CQRS pattern and how does NestJS support it?
- Advanced How do you implement gRPC in NestJS?
- Advanced How does NestJS handle graceful shutdown?
- Advanced What is custom provider syntax in NestJS (useClass, useValue, useFactory)?
- Advanced What is the difference between forRoot() and forFeature() in NestJS modules?