Astro middleware is a function exported as onRequest from src/middleware.ts that runs before a page or endpoint renders. It receives the request context and a next() function, so it can read cookies, attach data to context.locals, redirect, rewrite to another route, or change the response headers on the way out.
This guide covers how Astro middleware works in Astro 7, when it runs for static and on-demand pages, and the patterns you will use most: auth checks, typed locals, security headers, rewrites and chaining several handlers.
Key Takeaways
- Export
onRequestfromsrc/middleware.ts(orsrc/middleware/index.ts) and wrap it indefineMiddleware()for types.- Every code path must return
next()or aResponse, or Astro throws “The middleware didn’t return aResponse.”- Put per-request data on
context.localsand type it inApp.Locals. Never reassignlocalsitself.- Prerendered pages run middleware once at build time, not per visitor. Request-time logic needs on-demand rendering and an adapter.
- Chain handlers with
sequence()fromastro:middleware.
What Astro middleware does
Middleware sits between the incoming request and the route that handles it. For each request, Astro builds an APIContext (the same object endpoints receive), calls your onRequest function with it, and waits for a Response. Inside the function you decide whether to continue to the page with next(), stop early with your own Response, or send the request somewhere else.
The context gives you everything a server needs: context.request, context.url, context.cookies, context.params, context.redirect(), context.rewrite(), context.locals, and context.isPrerendered. Pages read the same locals object through Astro.locals, which is how middleware passes data down without prop drilling.
Typical jobs for Astro middleware:
- Checking a session cookie and redirecting signed-out visitors
- Adding security or caching headers to every response
- Loading the current user once and sharing it with every component
- Rewriting legacy URLs or A/B variants without a redirect
- Logging timing for each request
If you only need redirects that never change, the redirects option in astro.config.mjs is simpler. Middleware is for logic that depends on the request.
Create your first middleware file
Astro looks for src/middleware.ts (or .js). If you prefer a folder, src/middleware/index.ts works the same way. Export a function named onRequest:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (context, next) => {
const start = performance.now();
const response = await next();
const ms = (performance.now() - start).toFixed(1);
response.headers.set('Server-Timing', `render;dur=${ms}`);
return response;
});
defineMiddleware() adds no runtime behavior. It types context and next so your editor knows what is available. The pattern above is the one to remember: call await next() to render the page, change the response, then return it.
The most common mistake is forgetting the return. A handler that calls next() without returning it ends with undefined, and Astro stops with the error “The middleware didn’t return a Response.” The fix is covered in detail in the middleware error tip.
When middleware runs: static vs on-demand pages
This is where most confusion about Astro middleware comes from. Middleware always runs, but when depends on how the route is rendered.
| Route type | When middleware runs | Can read real visitor cookies and headers |
|---|---|---|
| Prerendered (default in static output) | Once per page, at build time | No |
On-demand (output: 'server' or export const prerender = false) |
On every request | Yes |
| Prerendered page served later | Does not run again | No |
So in a fully static site, middleware can still add locals data that pages read during the build, but it cannot check who is visiting. An auth check in a static build would run once, against a build-time request with no cookies, and bake the result into HTML.
For request-time logic, render those routes on demand. That needs an adapter (Cloudflare, Netlify, Vercel or Node) and either output: 'server' or export const prerender = false on the specific pages. The Astro SSR guide walks through that setup.
Inside middleware you can branch on context.isPrerendered to skip work that only makes sense per request:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware((context, next) => {
if (context.isPrerendered) {
return next();
}
context.locals.country = context.request.headers.get('cf-ipcountry') ?? 'unknown';
return next();
});
Share data with locals
context.locals is a plain object that lives for one request. Anything you set in middleware is readable in pages, layouts, components and endpoints through Astro.locals or context.locals.
Type it once in src/env.d.ts so every file gets autocomplete:
// src/env.d.ts
declare namespace App {
interface Locals {
user: { id: string; email: string } | null;
country?: string;
}
}
Then set it in middleware:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getUserFromSession } from './lib/auth';
export const onRequest = defineMiddleware(async (context, next) => {
const sessionId = context.cookies.get('session')?.value;
context.locals.user = sessionId ? await getUserFromSession(sessionId) : null;
return next();
});
And read it in a page:
---
// src/pages/account.astro
export const prerender = false;
const { user } = Astro.locals;
---
<h1>Signed in as {user?.email ?? 'guest'}</h1>
Set properties on locals, never the whole object. Writing context.locals = { user } throws “locals must not be reassigned.” because Astro and integrations share the same object. See fixing the locals reassigned error if you hit it.
Protect routes with a redirect
An auth guard is the classic Astro middleware use case. Check the path, check the session, and either continue or return a redirect:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
const PROTECTED = ['/account', '/dashboard'];
export const onRequest = defineMiddleware((context, next) => {
const needsAuth = PROTECTED.some((p) => context.url.pathname.startsWith(p));
const session = context.cookies.get('session')?.value;
if (needsAuth && !session) {
const to = encodeURIComponent(context.url.pathname);
return context.redirect(`/login/?next=${to}`, 302);
}
return next();
});
context.redirect() returns a Response, so returning it satisfies the “must return a Response” rule. Remember that protected pages must be rendered on demand, otherwise the check runs at build time and the page is served to everyone.
For API routes, return a JSON error instead of a redirect:
// inside onRequest
if (context.url.pathname.startsWith('/api/') && !session) {
return new Response(JSON.stringify({ error: 'Unauthorized' }), {
status: 401,
headers: { 'Content-Type': 'application/json' },
});
}
Set headers on every response
Because await next() returns the rendered Response, middleware is a good single place for headers:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware(async (_context, next) => {
const response = await next();
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
response.headers.set('X-Frame-Options', 'SAMEORIGIN');
return response;
});
This only affects responses Astro’s server produces, which means on-demand routes. For a static site, set headers in your host’s config instead (a _headers file on Cloudflare Pages and Netlify, or vercel.json on Vercel), because prerendered HTML is served straight from the CDN.
Rewrite requests without redirecting
A rewrite serves a different route’s content while the browser keeps the original URL. There are two ways to do it in Astro middleware:
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
export const onRequest = defineMiddleware((context, next) => {
// Option 1: pass a path to next()
if (context.url.pathname === '/old-pricing/') {
return next('/pricing/');
}
// Option 2: context.rewrite() restarts routing for the new path
if (context.url.pathname.startsWith('/beta/') && !context.cookies.has('beta')) {
return context.rewrite('/beta-closed/');
}
return next();
});
next('/path/') continues through the remaining middleware and renders the new route. context.rewrite('/path/') re-runs the whole middleware chain for the new URL, which is what you want when earlier handlers (like auth) should apply to the destination too. Because it re-runs middleware, make sure the destination path does not match the same condition, or you create a loop. Use a redirect instead when you want search engines and browsers to see the new URL.
Chain several handlers with sequence()
Once middleware grows past a few concerns, split it into small functions and combine them with sequence():
// src/middleware/index.ts
import { defineMiddleware, sequence } from 'astro:middleware';
const timing = defineMiddleware(async (_ctx, next) => {
const start = performance.now();
const res = await next();
res.headers.set('Server-Timing', `total;dur=${(performance.now() - start).toFixed(1)}`);
return res;
});
const auth = defineMiddleware((ctx, next) => {
if (ctx.url.pathname.startsWith('/dashboard') && !ctx.cookies.has('session')) {
return ctx.redirect('/login/');
}
return next();
});
const headers = defineMiddleware(async (_ctx, next) => {
const res = await next();
res.headers.set('X-Content-Type-Options', 'nosniff');
return res;
});
export const onRequest = sequence(timing, auth, headers);
Handlers run in order on the way in and in reverse on the way out, like layers of an onion. timing wraps everything, auth can stop the chain early, and headers edits the response before timing sees it. Each handler follows the same rule: return next() or a Response.
Middleware and integrations
Integrations can register their own middleware with addMiddleware() in the astro:config:setup hook, choosing order: 'pre' or order: 'post' relative to yours. That is how i18n routing and some auth libraries hook in. If you set i18n.routing: 'manual', Astro expects you to provide the i18n middleware yourself and errors with “Enabled manual internationalization routing without having a middleware.” until you do.
Some adapters can also deploy middleware as a separate edge function, so it runs at the CDN edge before the request reaches your server function. That is an adapter feature, so check your adapter’s documentation for whether it applies to your host.
Performance tips
Middleware runs on every on-demand request, so keep it cheap:
- Return early for static assets and prerendered routes you do not need to touch.
- Avoid database calls for public pages; check the path before loading a user.
- Cache expensive lookups per request in
localsso components do not repeat them. - Keep heavy imports out of
src/middleware.ts; with classic middleware the file is bundled with your server routes.
Most marketing sites, portfolios and blogs never need middleware at all, because every page is prerendered and headers live in the host config. Every Komal theme is static output with no middleware, and you can add it later when a project grows an account area or API. If you are planning one of those, the Astro config docs show where output and adapters are set, and the official middleware reference lists every context property.
FAQ
Does Astro middleware work on static sites?
Yes, but only at build time. In static output, middleware runs once per page while Astro generates HTML, so it can set locals values that pages read during the build. It cannot see real visitors’ cookies or headers, because no server runs after deployment.
Where do I put middleware in Astro?
Create src/middleware.ts (or src/middleware.js) and export an onRequest function. A folder at src/middleware/index.ts also works and is handy when you split handlers into several files and combine them with sequence().
How do I pass data from middleware to a page in Astro?
Set a property on context.locals in middleware, for example context.locals.user = user, then read it in the page with Astro.locals.user. Declare the shape in App.Locals inside src/env.d.ts so TypeScript knows the type.
What is the difference between next() and context.rewrite() in Astro?
Both render a different route while keeping the browser URL. next('/path/') continues with the remaining middleware in the chain, while context.rewrite('/path/') starts the whole middleware chain again for the new path, so earlier checks such as auth also run against the destination.
Can Astro middleware run at the edge?
It can, depending on your adapter. Some adapters can deploy middleware as a separate edge function that runs before your server function. By default, middleware runs inside the same server function as your on-demand pages.