How to serve webpack gzipped file in production using nginx.

Webpack + Gzip + Nginx

If you are building a webapp that uses webpack bundler optimizing site compression is a so simple, gzip is effective way to save bandwidth and speed up your site.😎

Check the current bundle size of your app and review.For example i have compared a simple app with before and after compression.

Left ( Before gzip) Right(After gzip)

After gziping app’s size from 277KB to just ~91.2KB!🤔

Instead of generating bundle.js, generate bundle.js.gz using Webpack’s compression plugin.

const CompressionPlugin = require('compression-webpack-plugin')
module.exports = {
"plugins": [ new CompressionPlugin ]
}

After enabling build the app two files with bundle.js and bundle.js.gz will be generated.Keep the two files and copy all your bundled app to nginx root folder var/etc/www

But nginx will not picking compressed file by default will serve uncompressed js files.To enable compression, include the gzip directive with the on parameter.

Configuring Nginx’s gzip Settings 👋

Open /etc/nginx/conf.d provide below configuration .

server {
gzip on;
gzip_static on;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_proxied any;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
...
}

To send a compressed version of a file to the client instead of the regular one, set the gzip_staticdirective to on within the appropriate context.

In this case, to service a request for /path/to/bundle.js, NGINX tries to find and send the file /path/to/bundle.js.gz. If the file doesn’t exist, or the client does not support gzip, NGINX sends the uncompressed version of the file.

Note that the gzip_static directive does not enable on-the-fly compression. It merely uses a file compressed beforehand by any compression tool. To compress content (and not only static content) at runtime, use the gzip directive.

Save and close the file to exit.

To enable the new configuration, restart Nginx.

$sudo service nginx restart
Before gzip static on 277KB
After gzip static on 91.5KB

How to Verify Your Compression☝️

We can test this just like above checking in Network tab, by using curl on each of the test files and examining the output for the Content-Encoding: gzip header.

Now all out bundle should stay uncompressed. you should be able to find Content-Encoding: gzip header in the output.

If that is the case, you have configured gzip compression in Nginx successfully!👏👏👏

Conclusion

Changing Nginx configuration to fully use gzip compression is easy, but the benefits can be immense. Users with limited bandwidth also receive the site faster. Speed is gaining traction as an important part of modern web and using gzip is one big step to improve it.