1

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?

Aman Kumar
  • 15
  • 1
  • 6

1 Answers1

2

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

m90
  • 11,434
  • 13
  • 62
  • 112
  • Its working but I am getting an error `Cannot set headers after they are sent to the client` – Aman Kumar May 20 '21 at 10:38
  • 1
    I think you also need to use `status` instead of `sendStatus` as `sendStatus` already sends a body: https://expressjs.com/de/api.html#res.sendStatus – m90 May 20 '21 at 10:42
  • ohh, thanks a lot its now fixed. I was actually using status but idk why i wrote sendStatus here ..Again thanks – Aman Kumar May 20 '21 at 10:48
  • @AmanKumar, be aware express "json" method in its middleware also sends the response. So sometimes implementing a middleware needs some extra trick like overriding "json" method but authentication should not need these kinds of tricks. – raxetul May 20 '21 at 10:50
  • ohh.okok i will note it – Aman Kumar May 20 '21 at 10:55