DEV Community

Po-Hsiang (Matthew) Lu
Po-Hsiang (Matthew) Lu

Posted on

Use Nginx to serve static React site with gzip and HTTP2

Let's start with pre-compressing our React app when we run the build process. To do this, install a npm package.

npm install compress-create-react-app --save-dev
Enter fullscreen mode Exit fullscreen mode

Then, change the build script in package.json to below.

build": "react-scripts build && compress-cra"
Enter fullscreen mode Exit fullscreen mode

Whenever we run npm run build, our project will be built and compressed files will be created automatically.

Next, to serve our static files with gzip and HTTP2 using Nginx, we will need to check if we have the modules needed. The modules required are "ngx_http_gzip_static_module" and "ngx_http_v2_module". Run the following command and check if the output contains "--with-http_gzip_static_module" and "--with-http_v2_module".

sudo nginx -V
Enter fullscreen mode Exit fullscreen mode

Here is the server block of our Nginx configuration that enables gzip and HTTP2. Note that to use HTTP2, we will first need HTTPS. If HTTPS is not yet activated, follow the guide of Let's Encrypt.

server {
  listen 443 ssl http2;
  ssl_certificate /PATH/TO/YOUR/CERTIFICATE;
  ssl_certificate_key /PATH/TO/YOUR/CERTIFICATE/KEY;
  location / {
    gzip_static on;
  server_name YOURSERVERNAME;
Enter fullscreen mode Exit fullscreen mode

The gzip_static directive allows Nginx to serve files with .gz extensions, while the http2 activates the support for HTTP2.

Top comments (0)