Sling Academy
Home/Node.js/How to Use Interceptors and Guards in NestJS

How to Use Interceptors and Guards in NestJS

Last updated: January 01, 2024

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.

Next Article: How to Handle File Uploads in NestJS

Previous Article: How to Implement Microservices with NestJS

Series: Nest.js Tutorials: From Basics to Advanced

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates