Cache busting with CRA React - reactjs

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.

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

I had the same issue when I use create-react-app ( and deploy to heroku). It keeps showing the old version of my app 😡.
I found the problem seems to be on the browser side, it caches my old index.html with its outdated js bundle
You may want to add the following to your server side response header
"Cache-Control": "no-store, no-cache"
or if you are also using heroku create-react-app-buildpack, update the static.json file
"headers": {
"/**": {
"Cache-Control": "no-store, no-cache"
}
}
I think in this way you can still keep that poor service worker 😂, and the latest content will be shown on the N+1 load (second refresh)
Hope this helps...

As mentioned by some of the previous answers here, both the service worker and the (lack of) cache headers can conspire against you when it comes to seeing old versions of your React app.
The React docs state the following when it comes to caching:
Using Cache-Control: max-age=31536000 for your build/static
assets, and Cache-Control: no-cache for everything else is a safe
and effective starting point that ensures your user's browser will
always check for an updated index.html file, and will cache all of
the build/static files for one year. Note that you can use the one
year expiration on build/static safely because the file contents
hash is embedded into the filename.
As mentioned by #squarism, older versions of create-react-app defaulted to opt-out of service worker registration, while newer versions are opt-in. You can read more about that in the official docs. It's quite a straightforward process to match you configuration to the latest template if you started with an older version of create-react-app and you want to switch to the new behaviour.
Related questions:
How to avoid caching for create-react-app
ReactJS: How to prevent browser from caching static files?
how to clear browser cache in reactjs

If your problem is with resources statically referenced in index.html, such as .css files or additional .js files (e.g. configuration files), you can declare a React environment variable, assign a unique value to it and reference it in your index.html file.
In your build script (bash):
REACT_APP_CACHE_BUST={e.g. build number from a CI tool} npm run build
In your index.html:
<link rel="stylesheet" href="%PUBLIC_URL%/index.css?cachebust=%REACT_APP_CACHE_BUST%" />
The variable name has to start with REACT_APP_. More about environment variables in React: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables.

It appears that they changed from opt-out to opt-in with regards to the service worker. Here's the commit that changed the README and it has examples similar to Kerry G's answer:
https://github.com/facebook/create-react-app/commit/1b2813144b3b0e731d8f404a8169e6fa5916dde4#diff-4e6ec56f74ee42069aac401a4fe448ad

Related

React S3+Cloudfront Cache Invalidation issues

For the project, we tried to deploy the front-end React static files by using AWS S3 + cloudfront.
It worked at the first time, but there was an issue that even though we updated with new build, some of the contents were not updating.
For the updates, we tried using invalidation method in Cloudfront and set /index.html. However, it didn't work properly and didn't load the updated build file so we also tried to invalidate assets files and met this problem.
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec
Is there a way to cancel the invalidation that we already did or fix this issue?

Removing the need for pathing in cloudFront distribution of S3 bucket requiring .html at the end of the page name, in Next.js project

I have a Next.js, React, Ts project that exists on a S3 bucket as a static site and is distributed via cloudFront.
The problem I'm running into is for me to go a different page I have to append .html at the end of the page name.
So mysite.com/profile will return a <Code>NoSuchKey</Code> error, however mysite.com/profile.html will route me correctly.
Is there some way to remove this necessity?
If this is a next issue i'm using
npx next build
npx next export
To build and export the /out directory which I then upload to my S3 bucket
my next.config.js
module.exports = {
target: "serverless"
}
I had it like this as I was originally making use of serverless for Next but have since moved away from it as I'm largely making use of client-side rendering and don't need any of the features it was providing and I am still in the process of doing a cleanup on the project.
Routing in S3 is done with exact match of the file name. You can remove .html extension to use routing as you like. And set metadata Content-type to text/html, to view it properly in browser

React App in Azure Website caching issue, browser serves old version

I have a react app which works perfectly fine.
However we are pushing code after NPM BUILD and deploying the code manually via SFTP
We can see the JS and CSS files have different names.
However the browser keeps downloading css and js files form cache, even if I disable cache in the browser.
I tried deleting all files in FTP, and magically the website keeps working? so it looks all the files are retrieved from the browser cache even if nothing exists in the server
I tried stopping and starting the azure website, but didnt make any difference
I tried cleaning the browser, cache, history, etc, no difference.
I wonder if I need to setup something in web.config, or in Azure website settings to make this works
This seems to be not an issue with Azure app service (Web app), you need to remove the caching of the react app with the following steps
Step 1: adding the following to in index.html
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
Step 2: inserting the following to the js
import { unregister } from './registerServiceWorker';
and call
unregister()
Reference Answer
It depends on how your app is configured, but I would not recommend disabling cache on the JS & CSS. Instead, it's best to add some version-dependent information to the file name so every time the JS or CSS update the file name changes.
Last time I worked on a web project we had it such that our JS & CSS had a content hash at the end. Something along the lines of main.205199ab45963f6a62ec.js instead of just main.js. Also note that you don't even have to manage that hash yourself, as there are ways to get ASP.NET or webpack (etc...) to update the reference in the HTML/JSX for you.
Here's webpack's page about it: https://webpack.js.org/guides/caching/

React: Accessing a page outside React app, inside public folder

I have a React application created by create-react-app. The app works fine, but I have run into a problem
I need to test som ad things on a plain html site, no additional React code. The problem I have is that the ads.txt tags need to be crawled by Google, which can take up to 24 hours on a new page/URL, time that I don't really have.
So I did the following. In my repo under /public folder I added a folder /ad-test with an index.html inside. When I serve it locally using npm start and go to http://localhost:3000/ad-test, it works fine.
Great, I thought and deployed it to the production environment, but now when I try to go to http://[my-site]/ad-test or http://[my-site]/yo-test/index.html it does not work (I get the React 404 site that I created).
I looked here and if I understand correctly, it is not possible to do it the way that I tried since the build stage will not include the public folder. Am I correct in this?
Any idea how to solve this?
EDIT:
I have a good knowledge of React and React Router in general, the app already uses <Switch><Route ... /></Switch> with a catch-all route directing to Not Found Component and the bottom.
The problem I have is that we include some ad scripts from an ad provider. The ads are not displayed in the application (adblockers totally removed from browser etc.) and the provider thinks that we have made errors in the React code.
We don't think that we made any errors (the ads were displayed fine in our test environment but not in prod) and we have to prove that React is not to blame for the ads not showing.
To do this we created a static HTML file with all ads hardcoded, no React components or other things that might disturb. BUT, because of ads and Google crawlers and ads.txt, we need to have the static test page under the same domain as our main page/application.
This is why I ask if it is possible to somehow add a static HTML that can be reached from http://my.page/test-page.html without being "intercepted" by react router, i.e. it exists outside React but on the same server.
When you use react by create-react-app, it means you are building a single-page application.
What this means is that after running npm run build you will have a build folder with only one html file called index.html in that fold.
This index.html does not know and has no relationship with your added 'index.html' in ad-test folder.
If you want your ad-test html to be recognised by react, you need to make it a component of app.js and use react-router to give it a pathname.
It is very simple.
First, install react-router-dom;
Second, set up react-router-dom;refer to https://reacttraining.com/react-router/web/guides/quick-start
Third, give your add-test component a pathname.Your js code should look something like this:
<Route path='/ad-test' component={AdTest} />
IMPORTANT:
After you deploy your app, always remember you just built a single-page application.
You only have one html in your app.
Please make sure when you test your app after you deployed you must tell your service provider that no matter what pathname a user inputs in the address bar you always redirect it to the index.html
The build stage includes the public folder:
If you have a picture in the public folder, and this picture was imported to other components it will be shown after you run npm run build
Hope it helps.
Have you tried playing with webserver configurations? It is usually setup to redirect all traffic to index.html. Maybe exclude your static html path from redirection?
Place test-page.html in public folder like
public/path-to-static-html/test-page.html
Configure webserver for
directing all traffic to index.html EXCEPT /path-to-static-html which
will be directed to test-page.html.
For example, in case of Apache
you will be setting the DirectoryIndex directive.

react + webpack - pass POST data to build

Coming from a PHP background, I used to have an index.php which does two things:
serve the webpage if no parameters were set;
or serve JSON data when a specific POST parameter was included in the request.
Something like this:
// -- index.php
<?php
if ($_POST["some_parameter"]) {
...
echo json_encode(someArrayData);
exit(0);
}
?>
<html>
...
</html>
I have built the complete frontend application with npm, webpack, webpack-dev-server, and react. Having completed the first part, how can I effectively serve JSON data instead of HTML when a request includes a specific POST parameter?
I can see 2 ways of doing this:
Build the frontend as usual and everytime I build the bundle, modify index.html, inject my PHP code in it, and rename it to index.php. I then would have to run this folder via apache or nginx, so I'd be able to run the index.php script. This method is downright ugly and is probably the worst way to do it.
Run a separate PHP server which just serves data or redirects to the static webpack-generated build. All requests should then start from this server, and this server determines whether to serve data or redirect to the frontend. The problem comes to neatly passing the POST data received from the request to the static react app. As far as I know, the only way to do this would be to include a URL (GET) parameter to the redirect and manually parse it with javascript on the frontend. This is a dirty solution, in my opinion.
So, to summarize:
I need an efficient way to get POST data in a react/webpack/webpack-dev-server environment.
It should work with my hot-module-replacement dev setup.
I'm fine with switching to a node-based backend like express.
There shouldn't be any ajax involved in the static react app.
Any ideas? There has to be a way to do this properly.
UPDATE: I solved this by simply copying an index.php from my source directory to my build directory via the webpack config. I serve the build folder to a PHP server and keep a webpack --watch building my source.
I lose built-in features like auto-reload and css injection, but it's worth the convenience of not having to implement SSR for a very simple task (getting a single POST variable).
For anyone interested, I also added 2 npm scripts:
npm run start runs my original webpack-dev-server with hot-reload, serving static content including a static index.html file
npm run static runs the webpack --watch which copies the index.php file to the build directory
This lets me have hot-reloading when developing frontend, and allows POST data fetching when programming logic.
It's easy, convenient, and works on most web hosting providers.

Resources