Nothing Special   »   [go: up one dir, main page]

DEV Community

athul dominic
athul dominic

Posted on

React cache issue in new build

When a new build is deployed, some of the older code is updating due to cache (or some other unknown) issue. i have configured the webpack.config.js file as below by referring the internet.

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name].[contenthash].js",
    publicPath: "/",
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: "babel-loader",
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      // Add any additional loaders for other file types
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].[contenthash].css",
    }),
    // Add any other plugins you need
  ],
  // Add any necessary optimizations or other configuration options
};
Enter fullscreen mode Exit fullscreen mode

index.html

 <!-- adding for cache issues -->
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
Enter fullscreen mode Exit fullscreen mode

Kindly help with any correction to the above code, or any new other alternative solutions.
This is a urgent requirement

Top comments (3)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Setting Cache-Control to no-cache is the right approach, but it's in the wrong place. Or not the wrong place: It just covers the cache settings of the HTML page. Cache settings for the scripts, css, images, fonts, etc. is not being set.

What you must do is set this in the response header in response to the assets URL's. This is specific to the HTTP server you are using to serve your React application. If you are using Nginx, it is a one-line configuration change.

Collapse
 
athuldom profile image
athul dominic

for setting for assests url, do we need to set from frontend or backend (server side) ?

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

Back-end. Your HTTP server needs to add the Cache-Control HTTP header in the response to no-cache. This is sufficient so long your HTTP server calculates and sends the ETag header. Then you'll be in the ideal position.

Nginx calculates ETag's by default, I think, so it is a matter of adding the HTTP header. If you're not using Nginx to server your website, you need to search on how to do this in your server of choice.