8

I'm working on my project using ReactJS and I use create-react-app to create my app. After building project, I use my server to serve the build folder. And when I update my app, the browser of user still uses the old version of my app because it caches the static files (js, css). So is there any way to prevent browser from caching static files ? Thank you !

Phuong
  • 93
  • 1
  • 1
  • 5

3 Answers3

9

TLDR: You will want to send caching instructions via HTTP headers.

The Cache-Control header has several directives to control cache behavior, expiration, and validation.

Cache Behavior: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

Cache-Control: public resource can be cached by any cache

Cache-Control: private resource can only be cached by the browser

Cache-Control: no-store Sets the browser to always request the resource from the server

Cache-Control: no-cache This tells the browser to cache the file but not to use it until it checks with the server to validate we have the latest version. This validation is done with the ETag header. (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag)

Esther Cuan
  • 367
  • 1
  • 16
  • 2
    I found an article that explains this thoroughly: https://medium.com/@codebyamir/a-web-developers-guide-to-browser-caching-cc41f3b73e7c – Esther Cuan Jul 25 '18 at 17:39
1

Create react app provides service worker and this caches the various files on the client side. If you want you can unregister the service worker. But please note that you will not be able to serve your app in offline mode as in PWA's

1

Supposing you have disabled your pwa, you may want to add those lines in your public/index.html

<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
Poyoman
  • 1,652
  • 1
  • 20
  • 28
  • 1
    Using a meta tag like this is now discouraged and is not valid HTML5. Why? It’s not a good idea because only browsers will be able to parse the meta tag and understand it. Intermediate caches won’t. always send caching instructions via HTTP headers. – vsync Aug 22 '21 at 12:38
  • @vsync but how do you set request/response headers on pages when you aren’t necessarily making an xhr call? Also would these be request or response headers? – Chris Maggiulli Oct 28 '21 at 14:42