Search code examples
node.jsexpressexpress-jwt

express-jwt always return 401


I am trying to use express-jwt for jwt validation.

It is working but it gives only 401 status and not any custom validation message.

app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.status(402).send("invalid token...");
  }
});

app.get("/", jwt({ secret: "MY_SECRETT_KEY" }), (req, res) => {
  console.log('eeeeeeeeeeeeeeeeeeeeeee', req.user);
  res.json({ message: "success" });
});

It is not sending 402 status, but default 401 only.

Need some help in this.


Solution

  • app.get("/", jwt({ secret: "MY_SECRETT_KEY" }), (req, res) => {
      console.log('eeeeeeeeeeeeeeeeeeeeeee', req.user);
      res.json({ message: "success" });
    });
    
    app.use(function (err, req, res, next) {
      if (err.name === "UnauthorizedError") {
        res.status(402).send("invalid token...");
      }
    });
    

    Error handlers should be added at the end.

    You can imagine middlewares as steps in a stair and the error handler is the floor. You are the request and you are going down the stairs, when you trip/fail from one of the steps, you fall straight to the floor.