How to cache a file in CloudFlare, but not in browsers? I tried "Cache Everything". I tried "Cloudflare-CDN-Cache-Control". Can't figure it out :)

I have a typical SPA (index.html plus some JS and assets). My entire domain is all static content. All my assets have hashes in their filenames, so they can easily be cached by both browsers and Cloudflare. That works fine.

But I don’t want browsers to cache my index.html file, because it may change at any point and you can’t put a version has in an index.html file. So I set the “cache-control: no-cache” header.

The problem is, Cloudflare sees that header and decides it cannot cache my index.html file. That is not what I want - I want Cloudflare to cache it, and browsers to not cache it. So now I see “cf-cache-status: DYNAMIC” in my header for a GET request to index.html, which means it’s actually hitting my server for every request.

The documentation says “Use Page Rules to implement custom caching options.” Reading up on that, apparently I can use Page Rules to add the Cache Everything setting to HTML files. I did that, but now I see “cf-cache-status: EXPIRED” in the headers for index.html, which means it’s still hitting my server every request, I guess because it still sees my “cache-control: no-cache” and decides it can’t serve the cached page. So “Cache Everything” is not helping.

Reading further, I see the Cloudflare-CDN-Cache-Control header, which seems to be exactly what I want. I can set different cache-control values for Cloudflare and for browsers. So I set “Cloudflare-CDN-Cache-Control public,max-age=86400” in the hopes that Cloudflare will start caching my index.html file. But it seems to not matter - in my browser I still see “cf-cache-status: DYNAMIC”.

I’m not really sure how to debug this further. But at this point, I feel like I’m probably just doing something fundamentally wrong. Feels like what I want is the same thing nearly any SPA would want, so there is probably an easy and reliable way to achieve it. What am I missing? I just want “cache-control: no-cache” to be sent to the browser, and for Cloudflare itself to cache my index.html until my deploy script tells it to clear the cache.

I figured it out! The key is to set “Cache Everything” and Cloudflare-CDN-Cache-Control together, and also make sure the “Browser Cache TTL” setting is set to “Respect Existing Headers”.

2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.