Brotli compression in react-apps
What it is, why do we need it, and how to implement it.
What is Brotli?
Brotli is a compression algorithm and it’s been developed by Google and serves best for text compression. Nowadays it is supported by all major browsers.
Brotli is a data format specification for data streams compressed with a specific combination of the general-purpose LZ77 lossless compression algorithm, Huffman coding and 2nd order context modelling. Brotli is a compression algorithm developed by Google and works best for text compression.
Why do we need it exactly?
Most of the companies are customer-centric and they know what user experience means. So, brotli will provide performance improvements to the overall user experiences for the webpack powered website.
According to a study by Google, the session time increases up to 70% if the website loads within 5 seconds. So, here at Sendinblue, we know the importance of every second, and using Brotli compression over gzip we were able to save around 12–15% of load times.
How to enable react apps to serve brotli compressed files when served through Nginx with a fallback to Gzip
Let’s enhance the performance
It’s a two steps process
- Generate Brotli and Gzip compressed versions of files using webpack.
- Serve the correct version of files when requested over a network.
Node 10.16.0 and later has native support for Brotli compression in its zlib module.
- Webpack configuration
- Nginx configuration
That’s it. Those few lines enable the Brotli compression with fallback to the Gzip compression for all the static resources of your website.
Does your browser support Brotli?
Browsers that support Brotli send “br” along with ‘gzip’ in the accept-encoding request header. If Brotli is enabled on your web server, you will get a response in Brotli compressed format.
Why do we need the Gzip fallback?
As of now, most browsers support brotli, but yes not all, and gzip has been supported by all browsers.
We implemented brotli compression on multiple applications at Sendinblue and found encouraging metrics both on bundle size and on load time improvement. Sharing below some stats from one of our applications.
Bundle size is reduced by more than 70% compared to having no compression and by 12–15% when compared to Gzip compression
The load time, over different network connections, reduced by 7–15% when compared to gzip and by 48–82% when compared to no compression
These few lines of code will improve the performance of Webpack powered websites. Yes, there are many other performance improvements things also, which we will discuss in our upcoming blogs.