Express: How to protect multiple routes with JSON web token

375 Views Asked by At

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.

1

There are 1 best solutions below

5
Eric Guan On BEST ANSWER

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