Subscribe to my newsletter and never miss my upcoming articles

Recently I was working on one of my projects built using nextjs . I was using semantic UI library. Even the minified version is too big for production. (631kb) It was making my web app slow. I searched through the internet for ways to reduce the size. Then I found out about gzip. I can encode my web app using gzip which reduced the size of the app significantly. Let’s see how to do it.

What is needed on the prod server?

We need a reverse proxy. I was using NGINX.

Steps

Configure webpack to create gzip files. Configure NGINX to serve gzip content.

Step 1

We need to install a package compression-webpack-plugin. Go to next.config.js and add this plugin.

config.plugins.push( new CompressionPlugin({ test: /\.js$|\.css$|\.html$/ , }), );

The whole file will look like this

const withSass = require (‘@zeit/next-sass’); const withCSS = require (‘@zeit/next-css’); const CompressionPlugin = require (‘compression-webpack-plugin’) const nextConfig = { onDemandEntries: { maxInactiveAge: 50 * 1000 , pagesBufferLength: 5 , } } module .exports = { …withCSS(withSass({ target: ‘serverless’, webpack (config) { config.module.rules.push({ test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/ , use: { loader: ‘url-loader’, options: { limit: 8192 , publicPath: ‘/_next/static/‘, outputPath: ‘static/‘, name: '[name].[ext]' } } }) config.plugins.push( new CompressionPlugin({ test: /\.js$|\.css$|\.html$/ , }), ); return config; } }) ), ...nextConfig }

Now you will see when you build your project, you will get bundle.js.gz Now you only have to configure your NGINX Reverse proxy to serve .gz file first.

Step 2

Run vim_etc_nginx_sites-available_default . Add the below code in your 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;