Phuong
Phuong

Reputation: 103

ReactJS: How to prevent browser from caching static files?

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 !

Upvotes: 9

Views: 47107

Answers (4)

Diwakar Dayal
Diwakar Dayal

Reputation: 33

As other people pointed out you can use cache control if you are using vite then in vite.config.js or ts file you can add server: { headers: { 'Cache-Control': 'no-store', }, },

Upvotes: 0

Poyoman
Poyoman

Reputation: 1966

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" />

Upvotes: 1

R Jaya Kumar Reddy
R Jaya Kumar Reddy

Reputation: 19

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

Upvotes: 1

Esther Cuan
Esther Cuan

Reputation: 387

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)

Upvotes: 11

Related Questions