I have a react web app that's hosted through Azure App Service and it gets updated fairly frequently, however the browsers accessing the app seem to be caching the javascript/html files fairly aggressively, and so I have to constantly hard refresh/empty cache, as well as tell users of the app to do the same. I'd like to avoid end users having to manually clear their cache whenever a change goes out, is there a way for App Service to tell clients to invalidate their cache? I tried looking up how to set the Cache-Control header for App Service but it doesn't seem possible, does the app need to be behind an Application Gateway or an Azure CDN instance in order to do this? Is there a recommended approach for forcing clients to pull down the latest changes when a deployment goes through?
Asked
Active
Viewed 297 times
0
-
Add the following in index.html .And import { unregister } from './registerServiceWorkerin in js, call Unregister() – HarshithaVeeramalla-MT Jan 26 '22 at 18:30
-
@HarshithaVeeramalla-MT Hmm but won't that disable all caching entirely? Is there a way to only invalidate cache on a new deployment? – ROODAY Jan 26 '22 at 18:34
1 Answers
0
- Cache busting solves the browser caching issue by using a unique file version identifier to tell the browser that a new version of the file is available. Therefore the browser doesn't retrieve the old file from cache, rather makes a request to the origin server for the new file.
Clear Cache on build for React Apps.
Install
momentlibrary.In
package.jsonfile add the below code at the end of the file
"buildDate": ""
- Create a new file
update-build.jsPlace it in the main folder besidespackage.json.
write below code inupdate-build.js
const fs = require("fs");
const filePath = "./package.json";
const packageJson = JSON.parse(fs.readFileSync(filePath).toString());
packageJson.buildDate = new Date().getTime();
fs.writeFileSync(filePath, JSON.stringify(packageJson, null, 2));
const jsonData = {
buildDate: packageJson.buildDate,
};
const jsonContent = JSON.stringify(jsonData);
fs.writeFile("./public/meta.json", jsonContent, "utf8", function (error) {
if (error) {
console.log("An error occured while saving build date and time to meta.json");
return console.log(error);
}
console.log("Latest build date and time updated in meta.json file");
});
When ever a new build is generated call this file.
In update-build.js :
- We are generating a current date/time value in epoch.
- Updating that value in meta.json file. This file will be automatically generated every time a new build is created.
Now update your build command in package.json file as below:
"build": "node ./update-build.js && react-scripts build",
Please refer Clear Cache on build for React Apps for more information.
Run npm run build command and your build will be generated with new build date time.
Please refer SO thread for more details.
HarshithaVeeramalla-MT
- 3,013
- 2
- 2
- 9