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?
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.
stale-while-revalidate
a client-side header used alongside the server-side s-maxage
? Does Next.js support server-side stale-while-revalidate in an API route via a header? –
Museology © 2022 - 2024 — McMap. All rights reserved.
s-maxage
does not mean the same asmaxage
(see https://mcmap.net/q/936541/-caching-difference-between-s-maxage-and-max-age/733345); and the relevant spec would be 'HTTP', rather than 'HTML'. – Ensor