Astro

Astro middleware

Astro middleware is a function in src/middleware that runs before a route renders. It can read the request, add data for the page, redirect, or replace the response.

How it is measured

Export onRequest from src/middleware.ts, taking a context and a next function. Call next() to continue and return its response. Use sequence() to chain several. Anything stored on context.locals is readable in pages as Astro.locals.

Test by logging the pathname in the function and loading three routes. In a static build the code runs at build time for each page, with no real visitor headers. On a server build it runs for every request.

Worked example

A members-only archive site checks a session token in middleware. Requests to /archive/* without a valid token get a 302 to /login. The check costs 2 ms and protects 1,900 pages with one function.

The same site also adds a request ID to locals so every log line from a page can be traced. A static marketing page in the same project never sees a visitor, so the check there does nothing.

How it differs

Astro middleware sits in front of everything. Astro endpoints are the handlers at the end of a specific URL. Middleware excludes the response body for one route; an endpoint excludes the chance to touch other routes.

Common errors

Relying on middleware for access control on prerendered pages. Doing slow database work on every request. Forgetting to call next() and hanging the page. Mutating the response after it was sent. Putting route-specific logic in a global function.

In practice

Use middleware for auth checks, redirects, and locals that many pages share. Keep each function short and under a few milliseconds. Put anything specific to one URL inside that URL's file.

See also

Astro, Astro endpoints

Sources

Count this on a real site.

Watch my website