2

Supercharge your API with Compression

 3 years ago
source link: https://dev.to/mikeeason/supercharge-your-api-with-compression-4ikp
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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:

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 modeExit 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 modeExit fullscreen mode

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

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 modeExit 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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK