Search code examples
amazon-web-servicesheaderamazon-cloudfrontbrowser-cachettl

AWS CloudFront - Is there a way to force browser to always get data from CloudFront instead of using local cache?


Basically the question is in the title.

My browser serves the data from local cache every time, instead of going to CloudFront for it.

Invalidation on CloudFront side doesn't help (as expected).

The age header in response (from local cache) is stuck at value of 1796. Is it because it's loaded from cache, not CF? I thought it's supposed to get incremented as time goes.

If I clear up the browser cache, it naturally hits CloudFront, and does so every time when I refresh the page.

However if I don't refresh the page for sufficiently long period of time (2 weeks, in my case), then come back and refresh it, the browser starts serving it only from local cache again. Today is March 20, and the last time I refreshed the page was March 06, i.e 2 weeks ago, so last-modified is Mon, 06 Mar 2023 06:37:39 GMT

All the articles I found so far, explain how to reduce CloudFront's caching time, in order to hit S3 more often (it's accomplished by setting cache-related headers accordingly) but I couldn't find how to do the same with the browser's local cache.

Any hints or ideas on that?

(getting data periodically from CloudFront is fine too, no need to go to CloudFront every time. I just don't want the browser to ALWAYS look into local disk cache)


Solution

  • You can instruct the browser not to cache using the max-age cache-control directive, while instructing CloudFront to cache using the s-maxage directive.

    You can also use an ETag to have the browser always check with CloudFront, but not transfer any actual bytes if the content is unchanged.

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control