node.jsexpressroutesmiddleware

middleware for authorization to perform certain actions


I have implemented an API that is protected by JWT authorization layer. So on each endpoint before calling it I check that the user has a valid token before proceeding. It works flawlessly.

Now I want to add a new intermediate step for some endpoints.

  1. On the frontend the user hits a button to call one of these endpoints.
  2. the user is requested to insert his/her password just to confirm "are you sure you want to do this?"
  3. password is validated on the backend
  4. if password matches then the action requested is performed

My routes are defined this way

router.post('/updatePrjAttivo', verifyToken, updatePrjAttivo);

where verifyToken is the middleware for authentication. Question is: can I add a second middleware to this? Like:

router.post('/updatePrjAttivo', verifyToken, otherMiddleware, updatePrjAttivo);

where otherMiddleware is where I verify the password?

Reading answers to this question I understand that "next() : move control to next function in same route. case of multiple functions in single route." So i can chain as many functions as I want. Am I correct?


Solution

  • In short - yes, you can have as many middleware as you want handling a route. They are executed by order, and each middleware is responsible for calling the following one with next. If it doesn't call next (e.g., since the authentication or authorization failed), the chain is broken, and the following middleware is not called.