In NestJS, global interceptors can be used by registering them at the application's global scope. This means interceptors will be applied to every incoming request. Using multiple global interceptors is a common practice, as it allows handling cross-cutting concerns such as logging, error handling, and response transformation at the global level.
To register multiple global interceptors in NestJS, you can register them in the providers array of the main module (typically AppModule) using the APP_INTERCEPTOR provider. Here is an example of how to register multiple global interceptors:
typescriptimport { Module } from '@nestjs/common'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { LoggingInterceptor } from './interceptors/logging.interceptor'; import { TransformInterceptor } from './interceptors/transform.interceptor'; import { ErrorsInterceptor } from './interceptors/errors.interceptor'; @Module({ // ... other module metadata ... providers: [ { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor, }, { provide: APP_INTERCEPTOR, useClass: TransformInterceptor, }, { provide: APP_INTERCEPTOR, useClass: ErrorsInterceptor, }, // You can continue adding more global interceptors ], // ... other module metadata ... }) export class AppModule {}
In this example, we register three global interceptors: LoggingInterceptor, TransformInterceptor, and ErrorsInterceptor. They will be applied in the order they appear in the providers array.
After registering these interceptors, NestJS's dependency injection system ensures that these interceptors are triggered for each request. Note that the execution order of global interceptors is determined by their order in the providers array, and interceptors are executed in a stack-based manner, meaning the last registered interceptor executes first (on entry), while the first registered interceptor executes last (on exit).
In practice, interceptors can be used for logging (recording detailed information about requests and responses), response transformation (e.g., wrapping all responses in a consistent data structure), and error handling (capturing and formatting exceptions). Using global interceptors ensures that these concerns are consistently and efficiently handled throughout the application.