HomeTeamContact

How to use Interceptors in Nest.js

By Judy Jose
Published in NestJs
December 22, 2022
2 min read
How to use Interceptors in Nest.js

Introduction

Who should read this?

  • Devs who moved to TypeScript and Nest.js because of enough problems created in their life by writing Express and Node servers.
  • Devs who are interested in writing more mature and abstract code in nest.js.
  • Devs who got assigned to “somehow” implement interceptor in the morning by the Project Manager.

Pre-requisites.

Experience in Javascript, Express.js & Node.js writing Rest APIs using Controllers and schemas.

This will cover

  1. What is Nest.JS?
  2. What is Interceptor?
  3. Why and when use an interceptor?
  4. How to use an interceptor?

What is nest.js (If you already know the answer skip this)

Nest.js is a framework supported by typescript, Where you can implement the OOPS concept, Functional Programming and Function Reactive Programming skills. Ie, If you need to write a scalable and maintainable Node.Js server without breaking it while showing it to friends or clients, Nest.Js is your guy. Nest.js is used to write servers, While we say ‘servers’ it needs Controllers, Routes Schemas etc. Nest.js will force us to write these components in a standard structure. We cannot implement the folder structure from our youtube guru who posted ‘Learn complete Nodejs in 2 hours’.

Why and when to use an Interceptor

Let’s say you are writing a few routes to create or update or do any operation in your nest.js server and you would like to perform a common logic like logging every request and response coming into these routes. Writing a method and calling it everywhere in your controller is one method to achieve this, But this will make your code look ugly and hard to maintain. Exactly where an Interceptor comes into play.

Interceptors flow

How to use an Interceptor

Let’s write a helloworld Interceptor in Nest.Js

  1. Setup a basic Nest.JS project from the terminal/cmd by typing the following commands
$ npm i -g @nestjs/cli
$ nest new project-name
  1. Open the folder created by the nestjs cli in your favourite code editor I am using vscode here.

vscode project started

  1. Run the following command to start the project
$ npm run start:dev
  1. Open your browser and access http://localhost:3000

Hurray! You have successfully implemented your nestjs project

Now let’s implement an interceptor to print out HelloWorld every time you access the this page.

  1. Create a file called helloworld.interceptor.ts in the src folder.

helloworld interceptor file added

  1. Add the following code into helloworld.interceptor.ts
    import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
    import { Observable } from 'rxjs';

    import { tap } from 'rxjs/operators';
 
    @Injectable()
    export class HelloWorldInterceptor implements NestInterceptor {
        intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // This console.log() will work before entering the contoller
        console.log("Before entering the contoller")
        
        return next.handle().pipe( tap(() => 
            // This console.log() will run after the code executes logic from contoller
            console.log(`Hello World!`)
        ));
  }
}

interceptor code

  1. Now let’s tell the contoller to use this interceptor by @UseInterceptor() decorator

    Add @UseInterceptors(HelloWorldInterceptor) above @get method of app.contoller.spec.ts

    Do not forget to import UseInterceptor from @nestjs/common

Add interceptor to contoller

  1. Try to access localhost:3000 again and you can see the “hello world!” printed in the your editor console.

Use @UseInterceptor(HelloWorldInterceptor) on top of any controller and your interceptor will be executed every time the contoller is called.

Code is available in github repository : Github


Tags

#nestjs#interceptors
Previous Article
How to implement scheduler in Java using Spring boot
Judy Jose

Judy Jose

Web Developer

Quick Links

About UsContact Us

Social Media