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
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

Incredible Demos

  • By
    MooTools CountDown Plugin

    There are numerous websites around the internet, RapidShare for example, that make you wait an allotted amount of time before presenting you with your reward. Using MooTools, I've created a CountDown plugin that allows you to easily implement a similar system. The MooTools JavaScript The CountDown class...

  • By
    Cross Browser CSS Box Shadows

    Box shadows have been used on the web for quite a while, but they weren't created with CSS -- we needed to utilize some Photoshop game to create them.  For someone with no design talent, a.k.a me, the need to use Photoshop sucked.  Just because we...

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.

  5. Great to see KeyCDN get some love here. It’s ease of setup and simple Dashboard is why we use them for many of our sites.

    Quick question, is brotli supported by nginx since our servers are not apache?

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