Skip to content
Advertisement

Add authentication check on every child endpoint of a express router

I have a express router and I only want authorized users to access routes of that router. I am using passport middleware. So I can just add a check for req.user in every endpoint like:

JavaScript

I can add a check in every endpoint like this but is there any better way to do this?

Advertisement

Answer

You can factor the behavior out into a “middleware” and mount it for every route of a router by passing it to router.use():

JavaScript

In this particular case it would be important to mount the isAuthorizedMiddleware after the Passport one so that it does not reject every request upfront.

Middleware docs: https://expressjs.com/en/guide/using-middleware.html

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement