1 minute read

TIL that the express response object does not forward content bodies to requestors if the status code of the response is 204: No Content.

The Situation

I am currently creating an API for a side project of mine. I added a PUT method to one of the resource paths, and I thought that if the response was successful that I would return status 204: No Content. This would not only save extra bytes from being passed over the wire back to the requestor, but since PUT requests require the requestor to submit a full representation of the new state of the resource, the requestor already knows what the new desired state is and doesn’t need to be sent back the updated state.

I tried creating a response like this:

res.status(204)
  .json({
    status: 'success',
    data: [],
    message: `Successfully updated resource with id ${id}`
  })

When I tried testing the endpoint, though, I would just get the 204 response code with no response body at all! After a bit of research, I learned this was intentional: express response objects will not forward a response body if the response status code is 204 No Content. This makes sense, but was somewhat surprising.

I modified my response above to the following:

res.status(204).send()

Which will not construct an unnecessary response body that won’t be sent.

Bonus TILs

I also learned through this exploration that .json() will automatically send your response with the specified JSON body; if you just set a status code without a response body, you need to explicitly use .send() to send the HTTP response to the requestor.

There is also a res.sendStatus() method that will set the HTTP status code, and will send a string representation of the status code in the body. This could be useful for 404s or 500s, where you don’t want to send additional detail to the client, and just want a default string representation of the status code to be sent.

Updated:

Comments