Nikita SemenistyiTech Lead

How to handle HTTP codes in Express like a pro


Recently building web applications more and more often means building single page application on the client-side with use of 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 HTTP interface, especially status codes.

In fact before web services gained their popularity programmers used to serve ready web pages to 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 splitted into categories here.

Wide adoption of REST API changed everything. It defines certain codes which should be used along with different CRUD operations. So for example, code 201 is used after a successful creation of a resource, though in other cases of success code 200 is usually used. This made where to buy throw pillows status code a bit more complicated as it should have been specified explicitly every time an action was performed to a resource. That’s led to such kind of code in express apps:

That’s why I decided to create a module which will handle it - express-api-response. Module is implementing 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 suitable HTTP code. Here is code from previous example refactored utilizing EAR:

After we finished executing our asynchronous code, we called next function which passed 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 which 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 EAR module is simple in creating, understanding and using though, it facilitates the work with web services and so far I am using it in all my express projects.