Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @UseGuards and Middleware in nestJS

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.

like image 218
Anwarul Islam Avatar asked Dec 17 '22 15:12

Anwarul Islam


1 Answers

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.

like image 162
Jay McDoniel Avatar answered Dec 31 '22 08:12

Jay McDoniel