Interceptors and Middleware
6 min read
Interceptors and Middleware in NestJS
Welcome to this guide on Interceptors and Middleware in NestJS! We'll explore how these powerful features help you write cleaner, more maintainable, and scalable server-side applications. 🚀
1. Middleware: Express-style Request Interception
What is Middleware? 🤔
Middleware is a function that gets executed before your route handler. Think of it as a gatekeeper for incoming requests. It has access to the request and response objects and a special next() function. This next() function is your way of saying, "Okay, I'm done with my part, you can pass the request to the next in line." If you don't call next(), the request will just hang there, which is a bit awkward for everyone involved.
The Problem It Solves
Imagine you want to log every single request that comes into your application. Without middleware, you would have to add logging code to every single route handler. This would be incredibly repetitive and a nightmare to maintain.
How Middleware Solves It
With middleware, you can write the logging logic in one place and apply it to all the routes you want to monitor. This keeps your route handlers clean and focused on their specific tasks.
Creating Middleware
In NestJS, you can create middleware as either a function or a class.
Functional Middleware:
This is the simplest way to create middleware. It's just a function that takes req, res, and next as arguments.
// logger.middleware.ts
import { Request, Response, NextFunction } from 'express';
export function logger(req: Request, res: Response, next: NextFunction) {
console.log(`Request...`);
next();
}Class-based Middleware:
For more complex scenarios, you can use a class. This allows you to use dependency injection. The class must implement the NestMiddleware interface.
// logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log('Request...');
next();
}
}Applying Middleware
You can apply middleware to specific routes, all routes in a module, or globally.
To apply middleware, you need to use the configure method in your module file.
// app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';
import { CatsController } from './cats/cats.controller';
@Module({
controllers: [CatsController],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes(CatsController);
}
}2. Interceptors: Modifying and Transforming Responses
What are Interceptors? 🤔
Interceptors are a powerful feature of NestJS inspired by Aspect-Oriented Programming (AOP). They allow you to bind extra logic before and after method execution. This means you can transform the result returned from a function or an exception that is thrown.
The Problem It Solves
Let's say you want to wrap every response from your API in a consistent format, like { "data": ... }. Without interceptors, you would have to manually format the response in every route handler.
How Interceptors Solve It
Interceptors allow you to create a single piece of logic that can be applied across multiple routes to transform the outgoing response. This keeps your code DRY (Don't Repeat Yourself) and your responses consistent.
Creating an Interceptor
An interceptor is a class annotated with the @Injectable() decorator that implements the NestInterceptor interface. It has an intercept() method that takes two arguments: ExecutionContext and CallHandler.
// transform.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface Response<T> {
data: T;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
return next.handle().pipe(map(data => ({ data })));
}
}In this example, we're using the map operator from RxJS to transform the response.
Binding Interceptors
You can bind interceptors at the method, controller, or global scope using the @UseInterceptors() decorator.
// cats.controller.ts
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { TransformInterceptor } from '../transform.interceptor';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';
@Controller('cats')
@UseInterceptors(TransformInterceptor)
export class CatsController {
constructor(private readonly catsService: CatsService) {}
@Get()
async findAll(): Promise<Cat[]> {
return this.catsService.findAll();
}
}3. Handling Timeouts and Caching via Interceptors
The Problem with Long-Running Requests ⏳
Sometimes, a request might take too long to process, which can lead to a poor user experience and tie up server resources.
Solution: Timeout Interceptor
You can create an interceptor to automatically cancel requests that exceed a certain time limit.
// timeout.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
timeout(5000),
catchError(err => {
if (err instanceof TimeoutError) {
return throwError(() => new RequestTimeoutException());
}
return throwError(() => err);
}),
);
};
};This interceptor will throw a RequestTimeoutException if the request takes longer than 5 seconds.
The Need for Speed: Caching ⚡
For frequently accessed data that doesn't change often, you can use caching to improve performance. Instead of hitting your database every time, you can serve the data from a cache.
Solution: Caching Interceptor
NestJS provides a built-in CacheInterceptor that you can use out of the box.
First, you need to install the required package:
npm install @nestjs/cache-managerThen, import the CacheModule into your AppModule:
// app.module.ts
import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import { AppController } from './app.controller';
@Module({
imports: [CacheModule.register()],
controllers: [AppController],
})
export class AppModule {}Now you can use the CacheInterceptor on any route:
// app.controller.ts
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
@Controller()
@UseInterceptors(CacheInterceptor)
export class AppController {
@Get()
findAll(): string[] {
// This response will be cached
return [];
}
}4. The ExecutionContext: Understanding the Current Request State
What is the ExecutionContext? 🕵️
The ExecutionContext is a utility class that provides information about the current execution context. It's a powerful tool that you can use in your guards, filters, and interceptors to get details about the current request. It extends ArgumentsHost, which is a wrapper around the arguments passed to your handler.
The Problem It Solves
When building generic components like guards or interceptors, you often need to know more about the context of the request. For example, which controller and which handler method is being executed?
How ExecutionContext Solves It
ExecutionContext provides helpful methods to get this information:
getClass(): Returns the type of the controller class.getHandler(): Returns a reference to the handler method that will be invoked.switchToHttp(): Switches the context to HTTP and gives you access to the request and response objects.
Example: Using ExecutionContext in a Guard
Let's say you want to create a guard that only allows access to a route if a certain metadata key is present.
// roles.guard.ts
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
return matchRoles(roles, user.roles);
}
}In this example, we're using the reflector to get the roles metadata from the handler method. We then use switchToHttp() to get the request object and check if the user has the required roles.
References for Further Reading 📚
- NestJS Middleware: https://docs.nestjs.com/middleware
- NestJS Interceptors: https://docs.nestjs.com/interceptors
- NestJS ExecutionContext: https://docs.nestjs.com/fundamentals/execution-context
- NestJS Caching: https://docs.nestjs.com/techniques/caching
Challenge
Challenge
Your task is to implement and apply a custom logging middleware and a response transformation interceptor in a NestJS application. You will be working with a pre-defined AppController and AppModule.
Requirements:
Create
RequestLoggerMiddleware:- Create an
@Injectable()class namedRequestLoggerMiddlewarethat implements theNestMiddlewareinterface. - Inside its
usemethod, access themethodandoriginalUrlfrom the request object. - Ensure you call the
next()function to pass control to the next middleware in the chain.
- Create an
Create
ResponseWrapperInterceptor:- Create an
@Injectable()class namedResponseWrapperInterceptorthat implements theNestInterceptorinterface. - The
interceptmethod must transform the response stream. - Use the RxJS
mapoperator to wrap the original response data into a new object with the following structure:json{ "statusCode": 200, "data": <original_response_data>, "timestamp": "<current_iso_date_string>" }
- Create an
Apply Middleware in
AppModule:- Modify the
AppModuleto implement theNestModuleinterface. - Implement the
configuremethod withinAppModule. - Inside
configure, apply theRequestLoggerMiddlewareto all routes ('*').
- Modify the
Apply Interceptor in
AppController:- Use the
@UseInterceptors()decorator on theAppControllerclass to apply theResponseWrapperInterceptorto all routes handled by this controller.
- Use the
Expected result
Your final code should correctly define and apply both the middleware and the interceptor. The AppModule should implement NestModule and configure the middleware, while the AppController should be decorated to use the interceptor.
import { Injectable, NestMiddleware, Module, Controller, Get, UseInterceptors, NestModule, MiddlewareConsumer, ExecutionContext, CallHandler } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
class RequestLoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
// In a real app, you would use a logger service here.
console.log(`Request... ${req.method} ${req.originalUrl}`);
next();
}
}
@Injectable()
class ResponseWrapperInterceptor<T> implements NestInterceptor<T, any> {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map(data => ({
statusCode: context.switchToHttp().getResponse().statusCode,
data,
timestamp: new Date().toISOString(),
})),
);
}
}
@Controller()
@UseInterceptors(ResponseWrapperInterceptor)
class AppController {
@Get()
getData(): object {
return { message: 'Request Successful' };
}
}
@Module({
controllers: [AppController],
})
class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(RequestLoggerMiddleware)
.forRoutes('*');
}
}