Laravel/Php - How to serve gzipped content from S3

Until last month, our apps were serving JavaScript files from s3 without any compression and one of our customer asked us if we can enable gzip compression on the assets being served.

As much as I researched, I found there is no out of the box gzip compression for the files on Amazon S3, Digital Ocean Spaces or Vultr Objects etc. So I decided to gzip compress the content of file on my server's end and then upload the compressed version to s3.

Here's what my code looks like now (Laravel Example)

$disk = config(''); // Returns s3

$settings = $shop->app_settings(); // Returns an array of all the settings

$content = view()->make('scripts.settings', compact('settings'))->__toString(); // Loads a view with all the settings

$gzippedContent = gzencode($content); // gzip compress the content

$fileName = 'settings/' . $shop->domain . '.js';

// Here we upload the file to S3
$response = \Storage::disk($disk)->put($fileName, $content, [
    'visibility'     => 'public',
    'ContentType'    => 'application/javascript',
    'ContentEncoding'=> 'gzip',

The only thing I had to do was just use a simple Php function gzencode() and send ContentEncoding along with the put request.

As the result, the file size is now reduced by almost 40% and the app loads way faster than before.