This document explains the three core request enhancement mechanisms in NestJS: Guards, Interceptors, and Pipes. These components form an Aspect-Oriented Programming (AOP) pipeline that processes requests before they reach route handlers and responses before they are sent to clients. Together, they enable cross-cutting concerns such as authorization, logging, caching, transformation, and validation.
For exception handling that wraps this pipeline, see Exception Handling. For middleware that executes before this pipeline, see Middleware Pipeline. For data validation patterns using class-validator, see Data Validation and Transformation.
The Guards, Interceptors, and Pipes system forms a layered execution pipeline where each layer has a specific responsibility:
Sources: Diagram 5 from high-level architecture, packages/core/nest-application.ts396-448
The pipeline executes in a specific order:
Guards implement the CanActivate interface and determine whether a request should be processed by the route handler. They are primarily used for authentication and authorization logic:
Sources: packages/core/nest-application.ts438-448 packages/microservices/nest-microservice.ts237-253 packages/microservices/microservices-module.ts47-48
Guards are registered globally using useGlobalGuards():
| Application Type | Registration Method | File Reference |
|---|---|---|
| HTTP Application | app.useGlobalGuards(...guards) | packages/core/nest-application.ts438-448 |
| Microservice | app.useGlobalGuards(...guards) | packages/microservices/nest-microservice.ts237-253 |
The registration applies instance decorators if configured and tracks guards in the GraphInspector:
Sources: packages/core/nest-application.ts438-448 packages/microservices/nest-microservice.ts237-253
Interceptors implement the NestInterceptor interface and provide AOP capabilities. They can execute logic both before and after the route handler using RxJS operators:
Sources: packages/core/nest-application.ts424-436 packages/microservices/nest-microservice.ts217-235 packages/microservices/microservices-module.ts49-50
Interceptors can:
The interceptor registration follows the same pattern as guards:
Sources: packages/core/nest-application.ts424-436 packages/microservices/nest-microservice.ts217-235
Pipes implement the PipeTransform<any> interface and perform data transformation and validation:
Sources: packages/core/nest-application.ts410-422 packages/microservices/nest-microservice.ts192-210 packages/microservices/microservices-module.ts45-46
Pipes are commonly used with class-validator and class-transformer:
| Package | Purpose | Sample Reference |
|---|---|---|
| class-validator | Validate DTOs using decorators | sample/01-cats-app/package.json26 sample/11-swagger/package.json27 |
| class-transformer | Transform plain objects to class instances | sample/01-cats-app/package.json25 sample/11-swagger/package.json26 |
Sources: sample/01-cats-app/package.json25-26 sample/11-swagger/package.json26-27 sample/20-cache/package.json27-28
In HTTP applications, enhancers are registered through the NestApplication class:
Sources: packages/core/nest-application.ts396-448 packages/core/nest-factory.ts59-113
The registration process:
instrument.instanceDecorator optionApplicationConfigGraphInspector as orphaned enhancers with appropriate subtypesSources: packages/core/nest-application.ts488-496 packages/core/nest-application.ts396-448
Microservices support the same enhancer registration through NestMicroservice:
Sources: packages/microservices/nest-microservice.ts167-253 packages/microservices/microservices-module.ts31-66
The microservices context creates dedicated context creators and consumers for RPC pattern handlers:
RpcContextCreator coordinates all enhancersExceptionFiltersContext handles RPC exceptionsSources: packages/microservices/microservices-module.ts38-51
Both HTTP and microservice applications support instance decoration, allowing instrumentation of all enhancer instances:
| Configuration Option | Purpose | Application Point |
|---|---|---|
instrument.instanceDecorator | Function to decorate instances | packages/core/nest-application.ts488-496 |
| Applied to | Guards, Pipes, Interceptors, Filters | packages/core/nest-application.ts396-448 |
The decorator is applied during registration:
Sources: packages/core/nest-application.ts488-496 packages/microservices/nest-microservice.ts372-380
The enhancers are configured during application initialization but warnings are logged if registration occurs after initialization:
Sources: packages/microservices/nest-microservice.ts167-234
In microservices specifically:
Sources: packages/microservices/nest-microservice.ts167-234
In HTTP applications, enhancers are registered during the initialization phase:
Sources: packages/core/nest-application.ts176-197
The initialization sequence:
applyOptions() - Apply CORS and other optionshttpAdapter.init() - Initialize platform adapterregisterParserMiddleware() - Register body parsersregisterModules() - Register WebSocket and microservices modulesregisterRouter() - Register middleware and routescallInitHook() - Call OnModuleInit lifecycle hooksregisterRouterHooks() - Register exception handlerscallBootstrapHook() - Call OnApplicationBootstrap lifecycle hooksSources: packages/core/nest-application.ts176-216
Both Express and Fastify adapters support request/response hooks that integrate with the enhancer pipeline:
| Adapter | Hook Methods | Implementation |
|---|---|---|
| ExpressAdapter | setOnRequestHook(), setOnResponseHook() | packages/platform-express/adapters/express-adapter.ts84-101 |
| FastifyAdapter | setOnRequestHook(), setOnResponseHook() | packages/platform-fastify/adapters/fastify-adapter.ts284-302 |
Express Implementation:
The Express adapter registers hooks as middleware that wraps all requests:
Sources: packages/platform-express/adapters/express-adapter.ts67-82
Fastify Implementation:
The Fastify adapter uses Fastify's native hook system:
Sources: packages/platform-fastify/adapters/fastify-adapter.ts267-282
The base AbstractHttpAdapter defines the hook interface:
Sources: packages/core/adapters/http-adapter.ts158-160
These hooks are placeholders in the abstract class, implemented by concrete adapters to provide platform-specific integration points for the enhancer pipeline.
Sources: packages/core/adapters/http-adapter.ts1-193
Each enhancer type has a dedicated context creator that handles dependency injection and metadata resolution:
Sources: packages/microservices/microservices-module.ts42-51
The context creators:
NestContainer for dependency resolutionApplicationConfig for global enhancer configurationSources: packages/microservices/microservices-module.ts31-66
For microservices, the RpcContextCreator coordinates all enhancers:
Sources: packages/microservices/microservices-module.ts42-51
This creates a unified pipeline for message pattern handlers similar to HTTP route handlers.
Sources: packages/microservices/microservices-module.ts18-19
Several sample applications demonstrate Guards, Interceptors, and Pipes in practice:
| Sample | Features Demonstrated | Dependencies |
|---|---|---|
| 19-auth-jwt | Guards for JWT authentication | @nestjs/passport, @nestjs/jwt |
| 20-cache | Interceptors for caching | @nestjs/cache-manager |
| 01-cats-app | Pipes for validation | class-validator, class-transformer |
| 11-swagger | DTO validation with pipes | class-validator, class-transformer, @nestjs/swagger |
Sources: sample/19-auth-jwt/package.json1-69 sample/20-cache/package.json1-57 sample/01-cats-app/package.json1-71 sample/11-swagger/package.json1-54
Demonstrates guards for authentication and authorization using Passport strategies:
Sources: sample/19-auth-jwt/package.json25-26
Demonstrates interceptors for caching responses using cache-manager:
Sources: sample/20-cache/package.json22-26
Demonstrate pipes for input validation and transformation using class-validator and class-transformer:
Sources: sample/01-cats-app/package.json25-26 sample/11-swagger/package.json26-27
The application options interface supports enhancer configuration:
Sources: packages/common/interfaces/nest-application-context-options.interface.ts1-77
Key options affecting enhancers:
preview - When true, providers/controllers are not instantiated, affecting enhancer executioninstrument.instanceDecorator - Function to decorate all instances including enhancersabortOnError - Affects error handling in the enhancer pipelineSources: packages/common/interfaces/nest-application-context-options.interface.ts34-69
When preview mode is enabled, the application skips certain initialization steps:
Sources: packages/microservices/nest-microservice.ts125-128
This mode is useful for introspecting application structure without fully initializing it, which affects how enhancers are registered and executed.
Sources: packages/core/nest-factory.ts209-211
Guards, Interceptors, and Pipes work consistently across:
The same interfaces and registration patterns apply regardless of transport:
Sources: packages/core/nest-application.ts396-448 packages/microservices/nest-microservice.ts167-253
This unified approach allows business logic in enhancers to remain transport-agnostic while the framework handles protocol-specific details through the respective context creators and consumers.
Sources: packages/microservices/microservices-module.ts1-122
Refresh this wiki