What's the difference between an Interceptor, Filter and Middleware in Nest.js framework? When should one of them be used and favored over the other?
Thanks
Use Interceptors when bi-directional transformation is required. Use middlewares when you want to stick closer to the traditional (eg Express) way of building your web app or when you want to more broadly apply functionality to many handlers at once (there's less decorators floating around in your code).
An interceptor is a class annotated with the @Injectable() decorator and implements the NestInterceptor interface. Interceptors have a set of useful capabilities which are inspired by the Aspect Oriented Programming (AOP) technique. They make it possible to: bind extra logic before / after method execution.
By default, Nest makes use of the Express framework. As mentioned earlier, Nest also provides compatibility with other libraries such as, for example, Fastify.
NestJS is an open-source, extensible, versatile, progressive Node. Js framework for creating compelling and demanding backend systems. It's currently the fastest-growing Node. Js framework in TypeScript.
As you already implied with your question, all three are very similar concepts and in a lot of cases it is hard to decide and comes down to your preferences. But I can give an overview of the differences:
Interceptors have access to response/request before and after the route handler is called.
@UseInterceptors()
controller- or method-scopedapp.useGlobalInterceptors()
in main.ts
null
to []
or wrap result in a response object: users
-> {users: users}
I like that the registration is closer to the route handlers compared to middleware. But there are some limitations, for example, you cannot set the response code or alter the response with Interceptors when you send the response
with the library-specific @Res()
object in your route handler, see docs.
Middleware is called only before the route handler is called. You have access to the response object, but you don't have the result of the route handler. They are basically express middleware functions.
app.use()
in main.ts
index.html
, see this thread body-parser
or morgan
The registration of middleware is very flexible, for example: apply to all routes but one etc. But since they are registered in the module, you might not realize it applies to your controller when you're looking at its methods. It's also great that you can make use of all the express middleware libraries that are out there.
Exception Filters are called after the route handler and after the interceptors. They are the last place to make changes before a response goes out.
@UseFilters()
controller- or method-scopedapp.useGlobalFilters()
in your main.ts
index.html
.The basic use case for exception filters are giving understandable error messages (hiding technical details). But there are also other creative ways of usage: When you serve a single page application, then typically all routes should redirect to index.html
except the routes of your API. Here, you can redirect on a NotFoundException
. Some might find this clever others hacky. Your choice. ;-)
Middleware -> Interceptors -> Route Handler -> Interceptors -> Exception Filter (if exception is thrown)
With all three of them, you can inject other dependencies (like services,...) in their constructor.
For those of us who "get it" better visually, I've created this NestJs pipeline digram based on the latest v6.10
version. Please feel free to point out any inaccuracies. I'll review and update it promptly, if needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With