DEV Community

Cover image for Supercharge your API with Compression
Mike Eason
Mike Eason

Posted on

Supercharge your API with Compression

Performance is critical to any API, taking the time to reduce API response times to be as low as possible is absolutely worth the effort.

Take a look at this example API request in Solaris:

An API Response

The API response is 44.6kB with a time of 584ms. This isn't terrible but could be smaller and faster with compression.

Express Compression

If you're familiar with Node.js you have probably used Express.js at some time or another.

Express is extensible and has a large number of middleware libraries that can be bolted on. One such library is compression.

To install compression:

npm install compression
Enter fullscreen mode Exit fullscreen mode

Then its a case of simply calling the Express use function to register the middleware like this:

const express = require('express');
const compression = require('compression');
const app = express();

...

// Compress all responses
app.use(compression({
    threshold: 0 // Byte threshold (0 means compress everything)
}));

...
Enter fullscreen mode Exit fullscreen mode

Easy, right? Now calling the same API endpoint we get this:

The same API response, but smaller and faster

The response is now 8.1kB and a time of 101ms, that's over 5x faster than before!

Compressing Specific Responses

With the above code, we'll be compressing all responses, if for some reason you'd like to not compress a response from the API then we can override the filter function like this:

app.use(compression({
    threshold: 0,
    filter: (req, res) => {
        if (req.headers['x-no-compression']) {
            // don't compress responses if this request header is present
            return false;
        }

        // fallback to standard compression
        return compression.filter(req, res);
    }
}));
Enter fullscreen mode Exit fullscreen mode

Any API request with the x-no-compression header will be ignored.

And that's it, your API will now serve compressed responses and should now be performing even better than before!


In my spare time I develop an open source strategy game called **Solaris, check it out.

Top comments (1)

Collapse
 
hiweus profile image
Andre AL

Great! thanks for sharing. I already read something about that but never put in practice. I tested here on my own api and got transfered content 22x smaller. 😁