Get in touch
Thank you
We will get back to you as soon as possible
.pdf, .docx, .odt, .rtf, .txt, .pptx (max size 5 MB)

16.4.2015

3 min read

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:

app.post('/api/album', function(req, res, next){
    albumRepository.add(req.body, function(err, data){
        var status = err ? 400 : 201;
        res.status(status).json(data);
    });
});

app.delete('/api/album/:id', function(req, res, next){
    albumRepository.delete(req.params.id, function(err, data){
        var status = err ? 400 : 200;
        res.status(status).json(data);
    });
});

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:

app.post('/api/album', function(req, res, next){
    albumRepository.add(req.body, function(err, data){
        res.err = err;
        res.data = data;
        next();
    });
}, apiResponse);

app.delete('/api/album/:id', function(req, res, next){
    albumRepository.delete(req.params.id, function(err, data){
        res.err = err;
        res.data = data;
        next();
    });
}, apiResponse);

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:

var apiResponse = require(‘express-api-response’);

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

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

res.successStatus = 202;
res.failureStatus = 405;

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.

0 Comments
name *
email *