Recently I switched to nestJS for its decoration. But I found there are two things Middleware
and @UseGuards
. I worked with Middleware when I used expressjs only.
Now my concern is what is the actual difference between these two. In my case these look like the same.
Pipes
, Filters
, Guards
, and Interceptors
can all be thought of as "specialty middleware" in the fact that each of them serve their own purpose, while "middleware" on it's own is a very broad term.
Pipes are made for request validation and payload transformation. Serializing data to what you expect and not much more.
Filters are your error handling middleware. You can tell which routes to use specific error handlers and how to manage the complexities around each one.
Interceptors are your before-and-after middleware like logging requests, along with response mapping and cache management. The ability to run this before and after each request is very powerful and useful.
Lastly, and what your question pertains to, guards are your authentication middleware. They tell your server who is and who is not allowed to pass through to specified routes.
The quick answer is, there isn't necessarily a difference between a guard and a middleware function, but middleware is a much broader topic while a guard in NestJS is a very specific thing. The only other difference is when each class is called (middleware -> guard -> interceptor (before) -> pipe -> controller -> service -> controller -> interceptor (after) -> filter (if applicable) -> client)
Note: This is assuming an ExpressJS HttpAdapter and not a Fastify one. Fatify middleware works a little differently, and may not fully be compatible with the nest middleware structure. Hence, it is preferred to use the aforementioned classes.
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