Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache busting with CRA React

When I updated my site, run npm run build and upload the new files to the server I am still looking the old version of my site.

Without React, I can see the new version of my site with cache-busting. I do this:

Previous file

<link rel="stylesheet" href="/css/styles.css"> 

New file

<link rel="stylesheet" href="/css/styles.css?abcde"> 

How can I do something like this or to achieve cache busting with create react app?

There are many threads in the GitHub of create react app about this but no one has a proper/simple answer.

like image 747
Alfrex92 Avatar asked Apr 02 '18 03:04

Alfrex92


People also ask

How do I stop caching in React?

To clear browser cache in React, we can add meta tags inside the head tag to make sure that the content of the page isn't cached. in the head tag to set the cache-control response reader to no-cache . And the expires response header is set to 0 to make sure nothing is cached.

What is a cache bust?

Cache busting is a way to prevent browsers from caching your ad content. Cache busting adds a random string to your ad tag each time the tag fires — typically a random number. Because the tag has a different number each time, the browser sends a new request each time.

How do I cache pages in React?

Approach: Follow these simple steps in order to store single data into cache in ReactJS. We have created our addDataIntoCache function which takes the user data and store into the browser cache. When we click on the button, the function is triggered and data gets stored into the cache, and we see an alert popup.


1 Answers

EDIT: create-react-app v2 now have the service worker disabled by default

This answer only apply for CRA v1

This is probably because of your web worker.

If you look into your index.js file you can see

registerServiceWorker(); 

Never wondered what it did? If we take a look at the file it got imported from we can see

// In production, we register a service worker to serve assets from local cache.  // This lets the app load faster on subsequent visits in production, and gives // it offline capabilities. However, it also means that developers (and users) // will only see deployed updates on the "N+1" visit to a page, since previously // cached resources are updated in the background.  // To learn more about the benefits of this model, read {URL} // This link also includes instructions on opting out of this behavior. 

If you want to delete the web worker, don't just delete the line. Import unregister and call it in your file instead of the register.

import { unregister } from './registerServiceWorker'; 

and then call

unregister() 

P.S. When you unregister, it will take at least one refresh to make it work

like image 152
Kerry Gougeon Avatar answered Sep 24 '22 04:09

Kerry Gougeon