Ali Gajani
Ali Gajani

Reputation: 15091

How to enable gzip compression on API Gateway?

I am having a bit of a trouble enabling gzip compression on API Gateway. I am using Laravel Vapor, which uses AWS Lambda under the hood.

I have scoured the API Gateway console dashboard for the settings, but to no avail. I have CORS setup in my application and I have the following enabled:

'allowedHeaders' => [
        'Accept',
        'Accept-Encoding',
        'Authorization',
        'Access-Control-Expose-Headers',
        'Content-Type',
        'X-Requested-With',
        'Origin',
        'X-Shadow-Progress',
        'X-Socket-ID',
        'x-socket-id'
    ],

I was under the impression that setting Accept-Encoding in my backend would do the trick, but it simply doesn't work. Response headers never have Content-Encoding: gzip in them.

Upvotes: 1

Views: 2448

Answers (2)

James
James

Reputation: 16339

I run a number of projects on Vapor. I forget if we had to do anything special inside of API gateway to get this going, but I created a piece of middleware that gzips responses which does the trick for us:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class GzipEncodeResponse
{
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if (in_array('gzip', $request->getEncodings()) && function_exists('gzencode')) {
            $response->setContent(gzencode($response->getContent(), 9));
            $response->headers->add([
                'Content-Encoding' => 'gzip',
                'X-Vapor-Base64-Encode' => 'True',
            ]);
        }
        return $response;
    }
}

This checks that the request accepts gzip encoding and if so, gzips the response and adds some necessary headers to get this to work.

Update; Since writing this answer, I've realised that there isn't a much content on Google explaining how to do this. I've detailed this approach and a little more about what's going on in a blog post on my website.

Upvotes: 4

Jens
Jens

Reputation: 21500

AWS API Gateway does support compression (gzip and deflate). It is just a bit hard to find. You can enable it either through the gateways settings in the AWS console or the AWS CLI.

In the AWS Console select your API Gateway and then you can find it under Settings > Content Encoding (see image below).

how to enable compression in AWS console

Documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-enable-compression.html

Upvotes: 1

Related Questions