Our pages in Next.js are hosted in Azure and are cached by the Azure CDN as per company policy. Because we did not want to have double caching, we disabled static page generation using export const dynamic = "force-dynamic";
on every page, and we manage page caching only using the CDN. The company policy is asking us to have both the Cache-Control
and Expires
headers set on every returned page for the CDN to work correctly.
So what we did was to set the headers in the next.config.js
file like this:
async headers() {
return [
{
source: "/(.*)",
headers: [{
key: "Cache-Control",
value: `public, max-age=${CACHE_CONTROL_MAX_AGE_SECONDS}`,
}, {
key: "Expires",
value: new Date(Date.now() + CACHE_CONTROL_MAX_AGE_SECONDS * 1000).toUTCString(),
}],
},
]
},
I thought that this function would be called on every page request, but it seems to be called only once, when the Next server is started. So the Expires
header returned is wrong, it is based on the server start time, not the page request time.
How can I set the Expire
header time based on the page request and not the server start time?