Awesome File Compression and Delivery with KeyCDN and Brotli

By  on  

KeyCDN

I've seen the KeyCDN name around for years, mostly as a free content delivery network (CDN) for many open source JavaScript frameworks, and based on that alone I've always thought very well of them.  KeyCDN recently asked me to check out one of their latest features:  Brotli support.  Let's take a look at Brotli compression, how KeyCDN supports Brotli, and how you can get started making your website much faster in a matter of minutes!

Quick Hits

  • KeyCDN provides a 30 day free trial
  • KeyCDN delivers your web assets quickly and securely
  • KeyCDN has added Brotli support, allowing for even faster asset download with less bandwidth usage
  • KeyCDN's Brotli support comes at no cost -- it's been added for free!
  • KeyCDN lets you configure zones so different sections of your website can have different delivery settings
  • KeyCDN provides a Brotli testing tool to ensure your server supports Brotli

What is Brotli?

Brotli, a newer compression algorithm created by Google, allows for better file compression and thus less bandwidth usage and faster download speeds.   Brotli brags better compression than gzip.  Brotli enjoys support in all major browsers, recently including Safari, and a variety of support from popular server software like Apache, nginx, IIS, and Node.js (via shrink-ray).  The content-encoding for Brotli stream is br, and like many new web features, Brotli is only available over HTTPS.

Creating Brotli Resources with Gulp or webpack

Popular task runners like webpack and gulp have open source libraries to generate static Brotli assets.  Let's use gulp-brotli to generate Brotli-compressed assets for a website:

var gulp   = require('gulp');
var gulpBrotli = require('gulp-brotli');
 
return gulp.src('./src/**/*.{css,js,html}'')
        .pipe(gulpBrotli.compress({
            quality: 11, // Your quality setting
            extension: 'br'
        }))
        .pipe(gulp.dest('./dist'));

The code above finds all CSS, HTML, and JavaScript assets, and generates likewise Brotli-compressed files in a given output directory.  If you prefer to use webpack, brotli-webpackplugin is your ticket:

var BrotliPlugin = require('brotli-webpack-plugin');
module.exports = {
    plugins: [
        new BrotliPlugin({
            asset: '[path].br[query]',
            test: /\.(js|css|html|svg)$/,
            threshold: 10240,
            minRatio: 0.8
        })
    ]
}

Creating your Brotli-compressed static assets is only a minor adjustment to your existing build code!

Enabling Brotli on KeyCDN

KeyCDN supports the awesome Brotli compression format but it's not enabled by default, so you'll need to take a moment to enable the feature.  Click on any existing or new zone from within the KeyCDN dashboard and set the "Cache Brotli" setting to "enabled:

That's all you need to do within the KeyCDN panel.  One requirement on your side is that your origin server must support Brotli -- this ensures you can set the quality setting of your Brotli assets.  Apache's mod_brotli documentation provides numerous short sample directives for enabling Brotli support:

<IfModule mod_headers.c>
    # Serve brotli compressed CSS and JS files if they exist
    # and the client accepts brotli.
    RewriteCond "%{HTTP:Accept-encoding}" "br"
    RewriteCond "%{REQUEST_FILENAME}\.br" "-s"
    RewriteRule "^(.*)\.(js|css)"              "$1\.$2\.br" [QSA]

    # Serve correct content types, and prevent double compression.
    RewriteRule "\.css\.br$" "-" [T=text/css,E=no-brotli:1]
    RewriteRule "\.js\.br$"  "-" [T=text/javascript,E=no-brotli:1]


    <FilesMatch "(\.js\.br|\.css\.br)$">
        # Serve correct encoding type.
        Header append Content-Encoding br

        # Force proxies to cache brotli &
        # non-brotli css/js files separately.
        Header append Vary Accept-Encoding
    </FilesMatch>
</IfModule>

Server configuration of Brotli is fairly simple on all server platforms.  KeyCDN also offers a Brotli test utility to ensure that your server has Brotli properly configured.

Seeing Results

To ensure your Brotli-encoded assets are being properly served, open any asset request within your browser's developer tools and inspect its header; you should see its content-encoding set to br:

The short time it takes to configure your server's Brotli module and then enable Brotli within KeyCDN will have an instant impact for your users, both on mobile and desktop.

KeyCDN Giveaway!

KeyCDN is keen to prove how amazing they are: they're giving away two 1TB accounts to David Walsh Blog readers to give them a shot! Want to enter? In the comments section below, tell me about your favorite CDN feature. Whether it be Brotli, geolocated servers, or another feature, give it a shout and you'll be entered to win!

Developers go to CDNs to make their websites faster, so it's great to see KeyCDN offering new, advanced compression techniques with minimal developer setup and at no cost.  You know how much a service cares when they push to make your website better using edge features with little configuration and cost, and Brotli is just one key feature provided by KeyCDN.  If you're in the market for a CDN, have a look at KeyCDN!

Recent Features

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

  • By
    I&#8217;m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

  • By
    Create a Dynamic Table of Contents Using MooTools 1.2

    You've probably noticed that I shy away from writing really long articles. Here are a few reasons why: Most site visitors are coming from Google and just want a straight to the point, bail-me-out ASAP answer to a question. I've noticed that I have a hard time...

  • By
    Optimize Your Links For Print Using CSS â Show The URL

    When moving around from page to page in your trusty browser, you get the benefit of hovering over links and viewing the link's target URL in the status bar. When it comes to page printouts, however, this obviously isn't an option. Most website printouts...

Discussion

  1. Hristo Chakarov

    Well, my favourite features are:

    – Geolocation servers – after all, that’s what CDN was initially built for. Nothing can beat the closer DA location and the reduced network time.
    – File compression (GZip, Brotli)

    What I don’t like:

    – Image compression (quality loss, WebP serving, etc.) – sometimes this leads to unexpected behavior in client’s browser

  2. Robert B

    The latest KeyCDN feature is icing on the cake. The features most important to me are KeyCDN performance (http2, SSDs, GZip Compression, etc), security (free SSL, DDoS protection, block bad bots), and affordability (pay-as-you go, lower pricing than Cloudflare, MaxCDN, others). Enough said.

  3. My fav feature is Geolocation servers. Obsessing over geo-latency these days.

    And just today, I discovered about Brotli, so today when your email came in, it hit the right spot, haha.

    Would totally love to win the giveaway to do testing ✌️

  4. Torsten

    First: Great introduction to brotli ans KeyCDN.

    Second: A CDN allows give all users of our website the same speed, whereever they are. So geolocation servers ans additional compression are my favourite features.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!