Nikita SemenistyiCTO

How to handle HTTP codes in Express like a pro


Building web applications often means building single page application on the client-side with the use of a JavaScript framework of choice backed by some sort of API on the server, the most popular variant is RESTful service. It brought extreme popularity to the HTTP interface, especially status codes.

In fact, before web services gained popularity programmers used to serve ready web pages to the user. It means that HTTP status codes used were 200 for normally served page, 404 for not found page and one code no developer would want to see - 500. Probably that was making creators of HTTP very sad as they’ve prepared a lot of possible codes. You can find the list of them split into categories here.

The wide adoption of REST API changed everything. It defines certain codes that should be used along with different CRUD operations. So for example, code 201 is used after the successful creation of a resource, though in other cases of success code 200 is usually used. This made using status codes a bit more complicated as they should be specified explicitly every time an action is performed to a resource. This led to such kind of code in Express apps:

One might say that this is a shortcoming of the Express framework and you must use a more sophisticated framework instead. The thought might be natural, but having worked with various turnkey frameworks like Sails, Loopback or Feathers, I would choose Express without doubts. It keeps on proving that simplicity is the most desirable characteristic of software.

That’s why I decided to create a module that will handle setting HTTP codes in Express - express-api-response. The module is implementing the express middleware interface, which means that it can be used in HTTP request handling pipeline. The only thing you should do is attach data you want to submit and error if any to the response object and pass control further to EAR. It will send stringified JSON if present along with a suitable HTTP code. Here is the code from the previous example refactored utilizing EAR:

After we finish executing our asynchronous code, we call the next function which passes control to apiResponse function declared elsewhere in advance in the code:

Here is the table representing HTTP codes which EAR will choose depending on error and data presence:

image

If you want to customize a code sent to a user you may specify it on the res object:

Another option that may be applied is res.shouldNotHaveData. If it is truthy, then EAR will not consider absence of data as failure and will respond with success status.

Despite the fact that the EAR module is simple in creating, understanding and using, it nicely facilitates the work with web services and I am using it in all my express projects.