Alan Alan - 9 months ago 100
Javascript Question

Express: How to protect multiple routes with JSON web token

I'm really just looking for a way to clean up my code here. I have several routes like this, note that each route individually goes through the JSON web token verification process.

router.route('/some-route').post((req, res) => {
jwt.verify(req.body.token, secret, (err, decoded) => {
if (err) return console.log(err);
// do something
res.json({ some: 'response data' });
});
});

router.route('/some-other-route').post((req, res) => {
jwt.verify(req.body.token, secret, (err, decoded) => {
if (err) return console.log(err);
// do something else
res.json({ some: 'response data' });
});
});


Is there some other way? Some of my routes are approaching callback-hell levels of nesting, so it would be nice to eliminate this from every route.

Answer Source

Pretty sure you can tell the router to use the function as middleware. The function will be called for every route in router.

router.use((req, res, next) => {
  if(!req.body.token)
    return res.json({ message: 'Missing token.' });

  jwt.verify(req.body.token, secret, (err, decoded) => {
    if (err) return res.json({ message: 'Failed to authenticate token.' });
    // do something else
    req.decoded = decoded
    next();
  });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download