Search code examples
node.jsexpress-jwtnodejs-server

How to get status code in jwt token based error msg using nodejs?


I implemented JWT token authentication using node.js and MongoDB. It's working fine. Throwing error messages is also working fine (token invalid, JWT expired, JWT must be provided). But how do I get the appropriate HTTP status code in the error message automatically?

// jwt.js

function Verify_Token(accessToken) {
    jwt.verify(accessToken, config.get("jwtprivatekey"), function (err) {
        value = err

    });
    return value

}


Solution

  • jwt.verify wont return any numeric status code in case of error. As per the documentation of jsonwebtoken npm module, we can clearly see that it just return the below fields when it throws error.

    jwt.verify(token, 'shhhhh', function(err, decoded) {
      if (err) {
      /*
         err = {
            name: 'TokenExpiredError',
            message: 'jwt expired',
            expiredAt: 1408621000
         }
      */
      }
    });
    

    If you have to return some status code from your nodejs web server, you have to embedd the status code in http response along with the error message from jwt. Something like below.

    jwt.verify(token, 'shhhhh', function(err, decoded) {
      if (err) {
    
         err = {
            name: 'TokenExpiredError',
            message: 'jwt expired',
            expiredAt: 1408621000
         }
         return res.status(401).send(err)
      }
    });