How does HTTP header "cache-control: s-maxage=31536000, stale-while-revalidate" work?

5.7k views Asked by At

I'm using NextJS on my project. For every page requests it adds 's-maxage=31536000, stale-while-revalidate' cache-control rules in response. How are these 2 rules supposed to work together?

1

There are 1 answers

7
Sean W On

s-maxage and stale-while-revalidate are part of the cache-control HTTP header standard that instruct caching of web objects.

As your question alludes, they are allowed to be comma separated to achieve your desired caching strategy.

Cache-Control: s-maxage=1, stale-while-revalidate=60

The first value (s-maxage) is how long the object should be cached in seconds. It also "overrides max-age or the Expires header, but only for shared caches (e.g., proxies) and is ignored by private caches" - see HTTP expiration

The second value (stale-while-revalidate), if supported, is how long after the s-maxage expiration the object can be cached for until it needs to be requested from your site again.


Example

  • Initial request - content is cached with the above cache-control directives
  • Request between 1-60 seconds after the initial request - Displays the cached content - revalidates in the background
  • Request 60 or more seconds after the initial request - Cause the browser to request a new version of the content to serve.

Here is how to set caching headers in Next.js.

Here is a related post I made that highlights ISR process in Next.js.