Gzip/deflate content from AWS API Gateway using Serverless

Last year AWS released a little gem that I missed: amazon-api-gateway-supports-content-encoding-for-api-responses. I’ve put together this very short tutorial to avoid more people missing out on this. I’ll be using the Serverless framework in this tutorial, but I’ll show you how to activate this directly in API Gateway also.

Typically we want to compress content to minimise the time it takes for resources to load for our uses an by doing so giving the users a better experience in our applications. What we will achieve in this tutorial is the little green text saying “compressed” in the diagram below.

You will need to add a serverless plugin called serverless-api-compression:

Here is a full example serverless.yml, rows 5, 24 and 25 is what adds the content compression.

After you have deployed your API you should be able to see this option turned on in API Gateway. Go to AWS API Gateway and then click your API, then click on Settings on the left at the bottom. The Content Encoding enabled should be check and the minimum body should be filled with the value you specified.

Here is an example of fetching the same resource with and without content compression. The screen shots below are taken from chrome developer tools, as you can see chrome will specify content-encoding: gzip if the content is gzipped.

If we compare the two, we find out that 68739/91470 ≈ 25%! 25% less bytes to fetch is of course pretty sweat to achieve by just apply two lines of config!