cache-guide
cache-guide/cache-control

The Cache-Control header

The Cache-Control header field is used to store instructions (called directives) that inform the cache on what rules and guidelines to follow when caching data.

Cache in this context can be either a private cache (the client’s browser) or a public/shared cache such as a Proxy server or CDN.

Note: Cache-Control is a multi-value header, meaning it can accept multiple, comma-separated directives.

What does it look like?

Let's say you have built a news site, and want to serve clients the latest news, with some specific rules in place:

  • Your homepage will allow content to be cached for 10 minutes max, after which the client needs to ping the server to see if there is new content
  • You want to fetch the latest content in the background to provide a seamless user experience
  • If your content server breaks or errors, you still want to serve SOME content to clients, even if it is stale

Here's a header schema that satisfies these goals:

HTTP/1.1 200 OK
Date: Thu, 23 Sep 2023 12:00:00 GMT
Server: Apache
Content-Type: text/html; charset=utf-8
Content-Length: 8000
Cache-Control: max-age=600, stale-while-revalidate=60, stale-if-error=86400
  • max-age=600: This directive tells your browser and intermediary caches that the content can be cached for up to 600 seconds (10 minutes). It's a typical caching duration for the front page.

  • stale-while-revalidate=60: If the content becomes stale (older than 10 minutes), your browser and intermediary caches can still serve it for up to 60 seconds while they fetch a fresh copy in the background. This allows for a smoother user experience as the page doesn't wait for a complete revalidation.

  • stale-if-error=86400: If there is an error (like a server issue) when trying to fetch fresh content, your browser and intermediary caches can serve the stale content for up to 86,400 seconds (24 hours). This ensures that even if something goes wrong, users can still access the news.

cache-control directives:

For specific information on each, see directives below (source: MDN):


RequestResponse
max-agemax-age
max-stale-
min-fresh-
-s-maxage
no-cacheno-cache
no-storeno-store
no-transformno-transform
only-if-cached-
-must-revalidate
-proxy-revalidate
-must-understand
-private
-public
-immutable
-stale-while-revalidate
stale-if-errorstale-if-error