How to handle errors with Express-JWT How to handle errors with Express-JWT express express

How to handle errors with Express-JWT


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();});


this is my solution for individual routes.

function UseJwt(){    return [        jwtExpress({ secret: configuration.jwtSecret, algorithms: ['HS256'] }),        function(err, req, res, next){            res.status(err.status).json(err);        }    ]}

usage...

app.get(`/${prefix}/:user_id`,        ...UseJwt(),        async function (req, res) {                      // handle your code here.        })


You can create an express middleware just before the code you use to start express server.

// Global error handler that takes 4 arguments and ExpressJS knows thatapp.use((err, req, res, next) => {    res.status(err.status).json(err);});app.listen(3000);

I use that for apps use REST but you can use the same approach and modify what should happen based on your needs. If you use Jade template for instance then you need to populate the template with the data you want to show to end user and log the rest on your log file.

app.use((err, req, res, next) => {    res.locals.status = status;    res.render('error')});