0
0
NestJSframework~5 mins

Interceptor interface in NestJS

Choose your learning style9 modes available
Introduction

An interceptor lets you run code before or after a request in NestJS. It helps you change or log data easily.

You want to log every request and response in your app.
You need to modify the response data before sending it to the client.
You want to measure how long a request takes to complete.
You want to add extra headers to all responses.
You want to handle errors or transform exceptions in a common way.
Syntax
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class MyInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // code before request
    return next.handle().pipe(
      map(data => {
        // code after request
        return data;
      }),
    );
  }
}

The intercept method runs for each request.

Use next.handle() to continue the request and get the response as an Observable.

Examples
This interceptor logs a message before the request is handled.
NestJS
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> {
    console.log('Before handling request');
    return next.handle();
  }
}
This interceptor wraps the response data inside an object with a data key.
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(data => ({ data })),
    );
  }
}
Sample Program

This example shows a controller with a TimingInterceptor. It measures how long the request takes and adds that info to the response.

NestJS
import { Controller, Get, UseInterceptors, Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
class TimingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    return next.handle().pipe(
      map(data => {
        const timeTaken = Date.now() - now;
        return { data, timeTaken: `${timeTaken}ms` };
      }),
    );
  }
}

@Controller('hello')
@UseInterceptors(TimingInterceptor)
export class HelloController {
  @Get()
  getHello() {
    return 'Hello World!';
  }
}
OutputSuccess
Important Notes

Interceptors work with Observables, so you can use RxJS operators to change data.

Always call next.handle() to continue the request cycle.

You can apply interceptors globally, per controller, or per route.

Summary

Interceptors let you run code before and after requests.

They help with logging, transforming data, and measuring time.

Use the intercept method and return next.handle() with optional RxJS operators.