node.jshttp-cachingmax-age

Client keeps requesting assets event though Cache-Control havent expired


I have a simple Node server which sets the Cache-Control max-age to 1200seconds and the client requests an image. Even though the 1200 seconds havent passed, if i change the image from server and refresh the page, the image will be downloaded again (even though the 1200seconds havent passed). It is supposed to read from cache until it expires.

Here is the response header:

enter image description here

Why is this happening?


Solution

  • When you told the browser to cache, the response header includes a validator called Last-Modified. When the browser is reloading it can include this in the request to the server in an If-Modified-Since request when for the GET or HEAD request. That will cause the server to return 304 if the item has not changed.

    So it sounds like things are working as they are supposed to. The fact that you changed the file caused the server to say "yeah, this file was changed so the cache shouldn't be used. here's the latest one" because the Last-Modified value won't match.

    If you want to avoid this and rely on the cache timeout even if the file changes, you could change your server to make sure that the ETag and Last-Modified values never change for these files. But I would recommend letting it act this way and allow the new file change to take its place in the cache.

    See this tutorial for more details.