In NestJS, interceptors provide a powerful mechanism for intercepting and handling incoming and outgoing requests and responses. To access request content within interceptors, you must access the current execution context, which can be achieved by implementing the Interceptor interface and utilizing the ExecutionContext class.
Below are the steps to access request content in interceptors:
-
Create an interceptor: First, create a new interceptor by applying the
@Injectabledecorator and implementing theNestInterceptorinterface. -
Implement the intercept method: The
NestInterceptorinterface mandates implementing aninterceptmethod that accepts two parameters:ExecutionContextandCallHandler. -
Access the request object from ExecutionContext: The
ExecutionContextobject enables access to request and response objects. You can retrieve the current HTTP request object using theswitchToHttpmethod. -
Read request content: Once you have the request object, you can access its content through properties such as
body,query, andparams.
Here is a simple example demonstrating how to access request content in a NestJS interceptor:
typescriptimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable() export class LoggingInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const request = context.switchToHttp().getRequest(); const body = request.body; // Access request body const query = request.query; // Access query parameters const params = request.params; // Access route parameters console.log(`Incoming Request: ${request.method} ${request.url}`); console.log('Body:', body); console.log('Query:', query); console.log('Params:', params); // Proceed with request processing return next .handle() .pipe( tap(() => console.log(`Outgoing Response: The response has been sent.`)), ); } }
In this example, the LoggingInterceptor interceptor retrieves the current HTTP request via ExecutionContext, logs the request method, URL, body, query parameters, and route parameters. It then allows the request to continue processing with next.handle() and logs a message after the response is sent.
To integrate this interceptor into your NestJS application, register it in the module's providers array and activate it on controllers or specific routes using the @UseInterceptors decorator.