What is Interceptor in NestJS: Explanation and Example
interceptor is a special class that can run code before and after a method execution, allowing you to modify requests, responses, or handle extra logic. It acts like a middleman that can transform data or add behavior around your route handlers.How It Works
Think of an interceptor as a helpful assistant who stands between you and your friend when you pass a message. Before the message reaches your friend, the assistant can change or check it. After your friend replies, the assistant can also change or log the reply before it gets back to you.
In NestJS, interceptors wrap around the execution of route handlers or other methods. They can run code before the handler starts, after it finishes, or even replace the result. This lets you add features like logging, caching, or modifying responses without changing your main code.
Example
This example shows a simple interceptor that logs the time taken by a route handler to complete.
import { 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 now = Date.now(); return next .handle() .pipe( tap(() => console.log(`Execution time: ${Date.now() - now}ms`)), ); } } // Usage in a controller import { Controller, Get, UseInterceptors } from '@nestjs/common'; @Controller('hello') @UseInterceptors(LoggingInterceptor) export class HelloController { @Get() getHello(): string { return 'Hello World!'; } }
When to Use
Use interceptors when you want to add extra behavior around your route handlers without changing their code. Common uses include:
- Logging request or response times
- Transforming or formatting responses
- Adding caching logic
- Handling errors or exceptions globally
- Modifying request data before it reaches the handler
For example, if you want to measure how long each API call takes or add a common response format, interceptors are a clean and reusable way to do it.
Key Points
- Interceptors run before and after route handlers.
- They can modify requests, responses, or add side effects.
- They help keep your code clean by separating concerns.
- Use
@UseInterceptors()decorator to apply them. - They work with RxJS observables to handle async flows.