What is Astro's middleware system?

Answer

Astro supports middleware in SSR mode via src/middleware.ts. Middleware runs on every request before the page handler. Use cases: authentication, redirects, A/B testing, request logging. Example: import { defineMiddleware } from "astro:middleware"; export const onRequest = defineMiddleware(async (context, next) => { const session = context.cookies.get("session"); if (!session && context.url.pathname.startsWith("/dashboard")) { return context.redirect("/login"); } context.locals.user = await getUser(session?.value); return next(); });. context.locals: pass data from middleware to pages. sequence(): compose multiple middleware functions. next(): call the next middleware or page handler. Middleware can also rewrite responses: intercept the response from next() and modify headers or body. Available in Astro 2.6+, middleware makes building auth-protected apps straightforward without library boilerplate.