How to Use Interceptors and Guards in NestJS

Updated: January 1, 2024 By: Guest Contributor Post a comment

Overview

NestJS, a robust framework for building efficient and scalable server-side applications, provides features like Interceptors and Guards for handling requests and securing endpoints. This tutorial delves into their usage.

Introduction to Interceptors

In NestJS, Interceptors are used to add extra logic to the request handling pipeline. They are capable of binding extra logic before or after method execution, as well as modifying the result returned from a function or the exception thrown.

Here’s an example of a simple logging interceptor:

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 {
    console.log('Before...');

    return next
      .handle()
      .pipe(
        tap(() => console.log('After...'))
      );
  }
}

Working with Guards

On the other hand, Guards are responsible for authorization and enforcing whether a certain request can proceed or not. A guard can inspect a request and determine if it meets certain criteria before it’s handled by a route handler.

A basic implementation of a guard might look like this:

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise | Observable {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    // Check if the user's role meets the required criteria
    const hasRole = () => user.roles.includes('admin');
    return user && hasRole();
  }
}

Binding Interceptors and Guards

To apply an interceptor or guard, you may bind them globally, at a controller level, or at a specific route level using decorators.

For example, to bind the logging interceptor globally, you would modify your app module:

import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
  ],
})
export class AppModule {}

To apply a guard to a single route, you’d use the @UseGuards() decorator:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { RolesGuard } from './roles.guard';

@Controller('users')
export class UsersController {
  @Get()
  @UseGuards(RolesGuard)
  findAll() {
    // Your endpoint logic goes here
  }
}

Advanced Interceptor Strategies

Building on the basics, let’s implement a more advanced interceptor that not only logs the request time but also modifies the response:

// other imports omitted for brevity

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable {
    const start = Date.now();
    return next
      .handle()
      .pipe(
        map(data => ({
          data,
          timestamp: Date.now() - start,
        })),
      );
  }
}

Complex Guard Implementations

For more complex requirements, guards can perform async operations such as fetching user permissions from a database:

// other imports omitted for brevity

@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(private userService: UserService) {}

  async canActivate(context: ExecutionContext): Promise {
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    const permissions = await this.userService.getPermissions(user.id);
    return permissions.includes('write');
  }
}

Combining Interceptors

You can also combine multiple interceptors to take advantage of chaining capabilities. For instance, you could use a combination of logging, transforming, and caching interceptors to provide a robust set of pre- and post-execution logic.

Best Practices

When using interceptors and guards, it is important to consider the following:

  • Insure the least privilege principle for securing endpoints with guards.
  • Measure the performance impact of complex interceptors.
  • Keep interceptors focused on one specific purpose for maintainability.

Conclusion

In this tutorial, we’ve covered the basics of utilizing NestJS interceptors and guards, provided code examples, and discussed advanced practices. Interceptors and guards are powerful tools that offer fine-grained control over application flow and security, facilitating the development of robust, secure, and maintainable applications.