I'm writing a RESTful API in Nest, which I recently started using and love so far. However, I'm struggling with finding a clean pattern to handle 204 No Content responses for my GET routes. Any recommendations?
I'm a little surprised there isn't something built into the framework for returning 204 if the object returned by a GET controller method is empty -- if there is, I haven't found it yet. If there truly isn't, I'm also wondering if this is worth a feature request on GitHub.
I've tried the following:
@Response()
as a Controller method parameter, then using res.sendStatus(204)
if the response is empty. However, this requires me to manually send 200 responses too, whereas I'd like to still rely on the framework to handle the request-response cycle and keep my controller methods as clean as possible.NoContentException
for my exception filter to handle. Although it's odd to throw an exception for a successful response code, I think this is the way I'll proceed in the meantime since my exception filter is the last thing that will execute in the code I've written.Since v6.1.0 it is possible to set the response code in an Interceptor, see this PR.
Unfortunately, this does not seem to be possible yet. In the docs it says:
Often, your status code isn't static but depends on various factors. In that case, you can use a library-specific response (inject using
@Res()
) object (or, in case of an error, throw an exception).
You also cannot just set the response code in an Interceptor
without sending it (instead of sendStatus
) because, as Kamil said in this thread:
global response controller's logic is the last step performed just before sending a final result through the network (that's the place where default status codes come in).
So if you (understandably) don't want to use @Res
in every controller, an ExceptionFilter
seems to be the best option, although it does not feel perfectly right.
Since other people seem to have the exact same problem, a feature request might be a good idea. :-)
Looking at this example:
@Post()
@HttpCode(204)
create() {
return 'This action adds a new cat';
}
This is all you need to do. It return's 204 for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With