How to Prevent Image Caching in React.js and Next.js

How to Prevent Image Caching in React.js and Next.js

Several times when we are building an application we need to add user images such as profile pictures, thumbnails or any other image use-case. Here, in many cases when we replace an image with the same name, the browser still picks up the old one.

But What is Browser Cache?

The cache is a software or hardware component that is used to temporarily store values for faster future access. The browser cache is a small database of files that contains downloaded web page resources, such as images, videos, CSS, Javascript, and so on.

The browser requests some content from the web server. If the content is not in the browser cache then it is retrieved directly from the web server. If the content was previously cached, the browser bypasses the server and loads the content directly from its cache. This is the same issue we were facing the browser was bringing the image from the cache instead of the server because the file name was the same.

We were facing the same problem in our application - "Soshals" in the About section of our portfolio. Current Behavior -

There are two solutions -

  1. Rename the new image and change the image name in the code. But in our case, the backend API response was giving the same name every time we uploaded the image.

  2. The solution we used - write a javascript code so that the browser does not pick up an image from the cache and load it every time.

<Image
       src={
            coverImg.startsWith("/") ? `${
                  process.env.NEXT_PUBLIC_BASE_API_URL
               }/file/download/${localStorage.getItem(
                  "userId"
                )}/${useFor}/${coverImg.slice(1)}?${new Date().getTime()}`
              : coverImg
          }
          alt={"Selected image"}
          width={110}
          height={110}
          className="rounded-2xl aspect-auto object-cover"
        />
?${new Date().getTime()}

This single line the code solved our issue because now the browser was picking up new images every time we uploaded.

After Solving -

Hope this solves your issue, thank you :)