23 Nest JS How to use middleware in Nest JS and it's concept
ฝัง
- เผยแพร่เมื่อ 11 ต.ค. 2024
- #nodejs #nestjs #javascript
Middlewares are a very useful tool to control the behavior of your request lifecycle. Almost every framework will allow you to control the request using Middlewares and NestJs is no exception.
Code: my-lnk.com/218...
You can find me on:
Twitter: / amitavroy7
Discord: / discord
Excellent explanation
Bro thank you very much, very useful tutorial!!!
You're welcome!
very good content bro!
Glad you liked it
In the case of the token example, wouldn't it be best to use guard ?
Yes that also can be used.
thank you very very much brah!!!
You are welcome
How can I access params in middleware it is coming undefiend. Header, body and query is accessible but not the path params (ex. /v1/user/:userId), userId is not accessible in middleware.
You will get them inside the request object
Why not use a guard for it? What's the difference between middleware and guards in context of NestJS? Also to check JWT token, generally guards are used using PassportJS.
Your question is a genuine concern that many people including me had.
The framework docs also address this and i quote
middleware, by its nature, is dumb. It doesn't know which handler will be executed after calling the next() function. On the other hand, Guards have access to the ExecutionContext instance, and thus know exactly what's going to be executed next
@@amitavroydev Thankyou for the comment. So that means, a guard would have been better for this scenario, or when we need access to the execution context? I'll definitely be reading about it more.
thanks!
Welcome!
Hi sir,
I want to apply middleware to specific routes only, to check the user role by using user id from the headers token
i want to apply the middleware to some routes only to check the user role . how can do that ??
you registered to all the routes, how can we do ti for specific routes ??
Look at the second code example on this page: docs.nestjs.com/middleware
This should solve your problem.
please i need a full video that teaches nestjs
What I have is a series of videos
excellent, I don't know it has only a few likes!!
Thanks
How to get the user logged in value after token is validated in service module..for example if user is calling getAllRoles and validatation is successfull but in Role Module service i want to get the user logged in so that i can update the db who is changing the stuff...one way i no to use in each controller method user params but i want something like storage or i dont know which is directly accessable in any service
I have handled that thing in the JWT strategy. When the token is validated, we have the ability to enric the user object with whatever points you want to populate.
github.com/amitavdevzone/nest-js-quiz-manager/blob/master/server/src/modules/auth/jwt.strategy.ts
Check this file for reference. Should help