Purpose of immutable in cache-control header
Published on: (Updated on: )
The `immutable` directive in a cache-control header tells browsers and other clients—like proxies or Content Delivery Networks (CDNs)—that once they download a resource, they don't need to check if it's changed for as long as its max-age lasts. Simply put, when the immutable directive is used, browsers are informed that the resource won’t change over its max-age time. This way, after the first download, the resource is directly reused for later requests without asking the server if it’s still the latest version, even when a user decides to reload the page themselves.
Normally, hitting the refresh button or pressing F5 makes the browser ask the server for the newest content, ignoring what's in the cache. But, with `immutable` added to the resource’s cache control header, the browser understands it doesn't have to do that. Instead, it uses the cached version of the resource right away, no matter how users trigger reloads.
Adding `immutable` can lessen the server's workload and dramatically improve loading times during page refreshes, offering a smoother experience to users because their pages load faster.
It's common to use `immutable` for resources like versioned or fingerprinted files (e.g., compiled and hashed CSS and JavaScript files) which, by design, change their URL whenever their content changes, rendering them effectively immutable for the tenure of their caching period.
Take a look at how a cache-control header might use the `immutable` directive:
Cache-Control: public, max-age=31536000, immutable
Here's what each part in the above directive means:
public: This tells the internet that it's okay for this resource to be stored by any cache, not just the browser's. This includes common caches found on networks or within Content Delivery Networks (CDNs).
max-age=31536000: This sets how long the resource should be considered fresh, specifically for 1 year (which is 31,536,000 seconds in total). This means, after downloading it, the cached resource is viewed as current for this period without needing to be downloaded again.
immutable: This part instructs any client, like a web browser or a CDN, that once they have this resource, they don't need to double-check with the original server to see if it's been updated for as long as the `max-age` has not been reached.
By assembling these directives together, you set a rule that maximizes the use of the cache through lessening unnecessary server requests and ensures rapid access to static resources, simplifying web browsing and significantly cutting down on page load times.