Astro glossaryAstro middleware is a function in src/middleware.ts that runs before a page or endpoint renders. It can check the request, change the response, or pass data to the page.
Middleware in Astro is a function that runs before a page or endpoint is rendered, so it can inspect the request, change the response, or share data with the page. It lives in src/middleware.ts (or src/middleware/index.ts) and exports an onRequest() function that receives the request context and a next() function.
What it is used for
- Checking that a visitor is signed in before showing a page.
- Adding headers, such as security headers, to every response.
- Putting request data, such as the current user, on
context.locals, where pages read it asAstro.locals.
Several middleware functions can be chained in order with sequence(). On prerendered pages middleware runs once at build time; on on-demand pages it runs on every request, which is when cookies and request headers are available.
Source: Astro docs: Middleware.