Node.js - Return res.status VS res.status

Viewed 6190

I am curious about the difference of returning a response and just creating a response.

I have seen a vast amount of code examples using both return res.status(xxx).json(x) and res.status(xxx).json(x).

Is anyone able to elaborate on the difference between the two?

2 Answers

If you have a condition and you want to exit early you would use return because calling res.send() more than once will throw an error. For example:

//...Fetch a post from db

if(!post){
  // Will return response and not run the rest of the code after next line
  return res.status(404).send({message: "Could not find post."})
}

//...Do some work (ie. update post)

// Return response
res.status(200).send({message: "Updated post successfuly"})

As explained by @kasho, this is only necessary for short-circuiting the function. However, I would not recommend to return the send() call itself, but rather after it. Otherwise it gives the wrong expression, that the return value of the send() call was important, which it isn't, as it is only undefined.

if (!isAuthenticated) {
  res.sendStatus(401)
  return
}

res
  .status(200)
  .send(user)
Related