Interceptors
Interceptors are the most powerful form of the request-response pipeline. They have direct access to the request before hitting the route handler. We can mutate the response after it has passed through the route handler.
In NestJS,Interceptors are used to intercept the incoming requests and outgoing responses,allowing you to execute some code before or after the request is handled by the respective handler(controller method or provider method). Interceptors are commonly used for logging,transforming data,error handling,authentication,and other cross-cutting concerns.
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';import { Observable } from 'rxjs';
@Injectable()export class LoggingInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const request = context.switchToHttp().getRequest(); const method = request.method; const url = request.url; console.log(`Incoming Request: ${method} ${url}`);
// Continue with the request processing return next.handle(); }}Apply it to a controller:
import { Controller, Get, UseInterceptors } from '@nestjs/common';import { LoggingInterceptor } from './logging.interceptor';
@Controller('cats')export class CatsController { @Get() @UseInterceptors(LoggingInterceptor) findAll() { ... }}Here, we’re applying the LoggingInterceptor to the GET /cats route. Whenever this endpoint is hit, the request method
and URL will be logged.