How to handle errors with Express-JWT

Startec picture Startec · Dec 5, 2016 · Viewed 13.2k times · Source

I am trying to incorporate the express-jwt library and I do not quite understand how it's error handling works.

The documentation says:

Error handling

The default behavior is to throw an error when the token is invalid, so you can >add your custom logic to manage unauthorized access as follows:

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

But I am confused how that works. If I have a simple req res situation, and I want to call next if the token is valid, or call next with an error if it is not, where to I put that app.use function?

For instance, here is my code:

router.post('/', expressJwt({  
  secret: jwtSecret,     
  credentialsRequired: false  
}), (req, res, next) => {   
  databaseController.findUser(req.user.email, (err, user) => {          
    if (err) {          
      return next(err)      
    }                        
    res.json(user)     
  })         
})

The err here would come from my DB call, not from the express-jwt validation. Any help is appreciated.

Answer

Amruta-Pani picture Amruta-Pani · Apr 3, 2017

Another way is you could place the middleware with app.use to scan all the routes for a valid jwt in the header or the query string. Any public endpoints can be exempted using the unless keyword. Ex:

app.use(expressjwt({credentialsRequired: true, secret: config.TOKEN_SECRET, requestProperty: 'user'}).unless({path: config.PUBLIC_URLs}));

app.use(function(err, req, res, next) {
    if(err.name === 'UnauthorizedError') {
      res.status(err.status).send({message:err.message});
      logger.error(err);
      return;
    }
 next();
});