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:

router.get("/", async (req, res) => {
  if (!req.user) {
    return res.sendStatus(401).send({ message: "Unauthorized" });
  }
  //logic 
  res.sendStatus(200).send({message: "OK"})
});

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():

function isAuthorizedMiddleware (req, res, next) {  
  if (!req.user) {
    return res.status(401).send({ message: "Unauthorized" });
  }
  next();
}

router.use(isAuthorizedMiddleware);

router.get("/", async (req, res) => {
  //logic 
  res.status(200).send({message: "OK"})
});

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

Advertisement