#Middleware isSSR
5 messages · Page 1 of 1 (latest)
Hi @hoary seal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Short answer: use the middleware context to check whether the current route is being prerendered (SSG) or rendered on demand (SSR).
Astro’s middleware receives an APIContext-like object. While the docs don’t list a dedicated “isSSR” flag, they show and rely on context.isPrerendered to detect prerendered requests. If context.isPrerendered is true, the render is happening at build time (SSG). If it’s false, the request is being served on demand (SSR). [Middleware exports; Middleware guide]
Example:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, next) => {
if (context.isPrerendered) {
// This request is for a prerendered (SSG) page
} else {
// This request is on-demand SSR
}
return next();
});
Notes:
- Middleware runs at build time for prerendered pages and at request time for on-demand pages. [Middleware intro]
- If you deploy with Netlify/Vercel edge middleware, it still distinguishes prerendered vs on-demand; locals are serialized and passed along for on-demand rendering. [Netlify usage; Vercel edge]
If you need to branch inside endpoints instead of middleware, endpoints also receive a context object “with properties similar to the Astro global,” applicable in SSR mode. [Server endpoints; Astro context]
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@hoary seal Kapa.ai is still learning and improving, please let me know how I did by reacting below.