DEV Community

loading...

Cache Control for React App with Nginx

Chanvin Xiao
Web / Full Stack / DevOps
・2 min read

The cache issue which typical React App confronts, can be solved by Nginx configuration

Common Deployment

After the app is built, we can just use Nginx to point to the static files

server {
  listen 80;
  root /PATH/TO/APP/build;
  try_files $uri $uri/ /index.html;
}
Enter fullscreen mode Exit fullscreen mode

Cache Issue

When access page for the first time, all the page and resources are from server, as the following image shown:

Close the browser, then reopen, Input address, press Enter, the browser will get the cache from local, as the following image shown:

Even if the page was updated between the two request, the browser would not get the update from the server, since disk cache does not communicate with server

Solution

If the resource file is updated, the file name will changed, so the cache of resource won't be a problem, we just need to disable the cache of page

Just replace

  try_files $uri $uri/ /index.html;
Enter fullscreen mode Exit fullscreen mode

With

  location / {
    if ( $uri = '/index.html' ) {
      add_header Cache-Control no-store always;
    }
    try_files $uri $uri/ /index.html;
  }
Enter fullscreen mode Exit fullscreen mode
  • Since all the pages is eventually pointed to the entrance file, so all the actual $uri are /index.html for pages
  • no-store is the strictest value for Cache-Control to disable cache, to make sure the browser won't use any cache
  • Since add_header with if can not be placed directly inside server, so we need to add the location layer

Result

This way, when we request page the second time, the page won't cache, but the resources will be cached if no change, as the following image shown:

You can access the following address, try to operate, and inspect the corresponding network request:

http://react.chanvinxiao.com

Summary

  • Weird cache problem will arise when input address and press Enter in browser
  • We can determine if the request is page through $uri of Nginx
  • The Cache Control header can be set via add_header of Nginx

Discussion (0)