NestJS Middleware vs Interceptors vs Filters

Tim Akhalaya
3 min readOct 21, 2023

--

Prerequisites: Application(s) written in NestJS

If you’ve been working with Express and now decided to switch to NestJS or maybe you are starting from a NestJS right away, the concept of Middleware/Filters and Intercepters might be a hard thing to grasp.

Today we are going to skip all the “non-useful” information that you can read in official NestJS documentations and focus on a few things :

  • When execution takes places ? (Before route handler, Before a Guard, Before a Pipe and etc.)
  • Do we have access to request and response

Below, we will follow the order in which each of the “modifiers” reaches the request

Middleware

If you like me, coming from the Express background, then the concept of the middleware won’t be a “surprising” thing.

  • Middleware is just a function which is called before a route handler.
  • We have access to both request and response

Here is the most basic example of the middleware

Defining our own Middleware
Defining our own Middleware

In order to actually use the middleware we use a function called configure inside of the dedicated module

Here i’m using a configure function in order to implemet a few middleware for * (all) routes dedicated to that module
Applying our newly defined middleware

Above, I’m applying a few middleware AsyncContextMiddleware, TracingMiddleware and Pino , please not that you can also configure for which route(endpoints) you would like these Middleware’s to be applied.

Interceptors

An Interceptor is just a class that is injectable (decorated with “@Injectable”) and implements NestInterceptor interface.

  • Executed after Middleware after Guard and Before and After Route handler
  • We have access to both request and response

Very useful when you need to bind some extra logic after the method execution.

Filters

Filters or ExceptionFilters is just the way to handle the exception inside of the application. NestJS comes with exceptions layer built-in.

  • After the route handler
  • We can get access to both request and response via context

In order to route the exception to the correct filter or in other words in order for the exception to be handled by the dedicated filter , you need to defined the Errors first.

Defining Extended Error Class
Defining Extended Error Class

In the example above we are defining the new extended Errors class and then we should be able to define the Filter for our “Extended Error” class.

Defining our own Exception filter
Defining our own Exception filter

Don’t forget to add catch decorator, otherwise you “Extended Errors” won’t land in this Filter.

And now looks like we are almost good to go with Filters, we just need to globally register the filter

Registering our filter in the main bootstrap file
Registering our filter in the main bootstrap file

I hope you enjoyed reading 😊

--

--