Validating routes in Express/Node

How important is it to validate a route? e.g. to serve a 404 if a route parameter is garbage?

I have written the following code


router.post('/questions/:qid/answers/:answerid/vote-:dir', (req, res, next) => {

  if (req.params.dir !== ("up" || "down")) {
    var error = new Error("😞 Not Found 😞");
    error.status = 404;
    next(error);
  }
  else if (isNaN(parseInt(req.params.answerid, 10))) {
    var error = new Error("NOT FOUND!");
    error.status = 404;
    next(error);
  }
  else { next(); }
} , (req, res) => {
  // actual response
});

Is this standard practice or do most people not bother?

Yes, it’s standard practice to validate requests. Try this, it’s a little simpler.

router.post('/questions/:qid/answers/:answerid/vote-:dir', (req, res) => {
  const params = req.params

  if(params.dir !== 'up' || params.dir !== 'down' || isNaN(params.answerid)) {
    res.status(404)
    res.send('Not Found')
    return // no reason to keep going
  }
  
  next()
}, (req, res) => {
  // actual response
})
1 Like

This does look a lot better - thanks! :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.