Skip to content

feat: middleware and virtual routes #7254

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Mar 11, 2024
18 changes: 8 additions & 10 deletions src/content/docs/en/guides/middleware.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,9 @@ i18nReady: true
---
import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro';

**Middleware** allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered.
**Middleware** allows you to intercept requests and responses and inject behaviors dynamically every time a page or endpoint is about to be rendered. This rendering occurs at build time for all prerendered pages, but occurs when the route is requested for pages rendered on demand.

This also allows you to set and share request-specific information across endpoints and pages by mutating a `locals` object that is available in all Astro components and API endpoints

Middleware is available in both SSG and SSR Astro projects.

:::note
On all prerendered pages, the middleware runs only during the **build process** to create static pages and does not run in the deployed website. This applies to all pages in a `static` (SSG) project. This also includes prerendered pages in `hybrid` mode (default) and any pages in `server` mode with `export const prerender = true`.

For on-demand rendered pages in `server` (default) or `hybrid` (with `export const prerender = false`) mode, the middleware runs in the deployed website when the route is requested.
:::
Middleware also allows you to set and share request-specific information across endpoints and pages by mutating a `locals` object that is available in all Astro components and API endpoints. This object is available even when this middleware runs at build time.

## Basic Usage

Expand Down Expand Up @@ -200,3 +192,9 @@ greeting response
auth response
validation response
```

## Error pages

Middleware will attempt to run for all on-demand rendered pages, even when a matching route cannot be found. This includes Astro's default (blank) 404 page and any custom 404 pages. However, it is up to the [adapter](/en/guides/server-side-rendering/) to decide whether that code runs. Some adapters may serve a platform-specific error page instead.

Middleware will also attempt to run before serving a 500 error page, including a custom 500 page, unless the server error occured in the execution of the middleware itself. If your middleware does not run successfully, then you will not have access to `Astro.locals` to render your 500 page.