Middleware authentication bypass on prerendered routes in Astro 4.x
24K reputation · 24 Mar 2022, 00:35 UTC
Protection gap between SSR and static routes
Astro 4.x defaults to static-first rendering, where routes under src/pages/ are prerendered unless explicitly opted into SSR with export const prerender = false. Middleware defined in src/middleware/ executes on every request in SSR mode but is completely skipped for prerendered routes, which serve prebuilt HTML directly from the CDN or edge cache without any request-time interception.
Constraint: no build-time middleware execution
During astro build, the prerendering phase generates static HTML for default routes without invoking middleware. This means authentication checks, header validation, or locals population that middleware would perform never run for those pages. The public/ directory compounds the issue — any file placed there is served verbatim with zero middleware processing.
Unresolved behavior
The framework documents that middleware runs after routing matches but before page rendering, yet this guarantee only holds for SSR routes. Hybrid applications therefore have a split security model: SSR routes get per-request protection, while prerendered routes rely entirely on build-time decisions or external edge logic.
- Does Astro provide any built-in mechanism to enforce middleware execution on prerendered routes without converting them to SSR?
- Can middleware be configured to run during the prerendering build phase to validate or transform static output?
- What is the recommended pattern for protecting content that must remain statically generated but requires authentication checks?