Search code examples
cachingbrowser-cachecache-control

Does 'cache-control: public' actually have any effect?


Is cache-control: public, max-age=60 handled any differently by any known caches than cache-control: max-age=60?

I've struggled to verify it, but I assume that if any cache-control instructions exist on a response, then it is assumed that that response is cacheable by the browser and any intermediate caches unless cache-control: private is set.

Does this mean that cache-control: public is redundant? Isn't this the behaviour you'd get anyway?


Solution

  • On more careful reading of MDN, I think I've found the answer to my own question.

    TL;DR: cache-control: public will explicitly override the default rules for which sort of responses are considered cacheable, so shouldn't be used lightly. Many responses normally shouldn't be cached - e.g. POSTs or 302 redirects. See below for the full set of rules.

    From the cache-control page:

    public The response may be stored by any cache, even if the response is normally non-cacheable (emphasis mine).

    So what does "cacheable" mean? From the "cacheable" page on the MDN glossary:

    A cacheable response is an HTTP response that can be cached, that is stored to be retrieved and used later, saving a new request to the server. Not all HTTP responses can be cached, these are the following constraints for an HTTP response to be cached:

    • The method used in the request is itself cacheable, that is either a GET or a HEAD method. A response to a POST or PATCH request can also be cached if freshness is indicated and the Content-Location header is set, but this is rarely implemented. (For example, Firefox does not support it per https://bugzilla.mozilla.org/show_bug.cgi?id=109553.) Other methods, like PUT or DELETE are not cacheable and their result cannot be cached.
    • The status code of the response is known by the application caching, and it is considered cacheable. The following status code are cacheable: 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501.
    • There are (I assume this should be aren't) specific headers in the response, like Cache-Control, that prevents caching.

    So it looks like one should only use cache-control: public when they explicitly want to override these rules for cacheability, which in general is probably not a good idea.