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 ??
@amitavroydev Жыл бұрын
Look at the second code example on this page: docs.nestjs.com/middleware This should solve your problem.
@kelvinmandlik73952 жыл бұрын
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.
@amitavroydev Жыл бұрын
You will get them inside the request object
@GabrielLogan177 ай бұрын
In the case of the token example, wouldn't it be best to use guard ?
@amitavroydev7 ай бұрын
Yes that also can be used.
@zeroes52372 жыл бұрын
thank you very very much brah!!!
@amitavroydev2 жыл бұрын
You are welcome
@AmarjeetKumar-xr2gf2 жыл бұрын
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
@amitavroydev2 жыл бұрын
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
@syedazeemjaved9 ай бұрын
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.
@amitavroydev9 ай бұрын
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
@syedazeemjaved9 ай бұрын
@@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.