To create protected routes in Astro, add a src/middleware.ts file that runs before every request, checks whether the visitor is signed in (usually by reading a session cookie), and returns context.redirect('/login/') for protected paths when they are not. The protected pages must be rendered on demand, with an adapter installed, because middleware only runs at build time for prerendered pages.
Key Takeaways
- Middleware in
src/middleware.tsruns before every on-demand page and endpoint.- Match protected paths by prefix, check the session, and redirect or return 401.
- Store the signed-in user on
context.localsso pages can read it without repeating the check.- Protected pages need
export const prerender = false(oroutput: 'server'), or they are built once and served to everyone.
The middleware
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getUserFromSession } from './lib/auth';
const PROTECTED = ['/account', '/dashboard', '/api/private'];
export const onRequest = defineMiddleware(async (context, next) => {
if (context.isPrerendered) return next();
const path = context.url.pathname;
const needsAuth = PROTECTED.some((p) => path === p || path.startsWith(`${p}/`));
if (!needsAuth) return next();
const sessionId = context.cookies.get('session')?.value;
const user = sessionId ? await getUserFromSession(sessionId) : null;
if (!user) {
if (path.startsWith('/api/')) {
return new Response('Unauthorized', { status: 401 });
}
const target = encodeURIComponent(path + context.url.search);
return context.redirect(`/login/?next=${target}`, 302);
}
context.locals.user = user;
return next();
});
What each part does:
context.isPrerenderedistruefor static pages. Skipping them avoids running cookie logic during the build, where there are no cookies.- Matching
porp/stops/accountantfrom matching/account. - API routes get a
401instead of a redirect, because afetch()caller cannot follow a login page. nextcarries the original URL, so the login page can send people back where they came from. Validate it on the login page and only redirect to paths that start with/, or you create an open redirect.
getUserFromSession is yours: look the session up in your database, or use Astro sessions or an auth library. Our overview of Astro authentication options compares them.
Type locals
Tell TypeScript what lives on locals so pages get autocompletion:
// src/env.d.ts
declare namespace App {
interface Locals {
user?: { id: string; email: string; role: 'member' | 'admin' };
}
}
Set properties on locals; never reassign the object itself, which throws a “locals must not be reassigned” error. More on this in our guide to Astro locals.
Make the pages on demand
---
// src/pages/dashboard/index.astro
export const prerender = false;
const { user } = Astro.locals;
---
<h1>Welcome back, {user?.email}</h1>
If most of the site is static, add export const prerender = false to each protected page or endpoint. If most of it is private, set output: 'server' in astro.config.mjs and mark public pages export const prerender = true. Either way you need an adapter; see the no-adapter error fix if the build complains.
Forgetting this is the classic mistake. A prerendered dashboard is generated once at build time, with whatever the middleware saw then, and served as a static file to anyone. Middleware cannot protect it afterwards.
Role checks
Extend the same middleware for roles:
// src/middleware.ts (inside onRequest, after the user is loaded)
if (path.startsWith('/admin') && context.locals.user?.role !== 'admin') {
return new Response('Forbidden', { status: 403 });
}
Return 403 for signed-in users without permission and redirect only signed-out users. That keeps the meaning of each status code clear.
Combine several middleware functions
As rules grow, split them and chain them with sequence:
// src/middleware.ts
import { sequence } from 'astro:middleware';
import { auth } from './middleware/auth';
import { securityHeaders } from './middleware/headers';
export const onRequest = sequence(auth, securityHeaders);
They run in order, each calling next(). For redirect patterns beyond auth, see redirecting from middleware, and our Astro middleware guide covers the full API. If you are starting from one of our Astro themes, all pages are static, so add an adapter before adding protected areas.
FAQ
How do I protect a route in Astro?
Add src/middleware.ts, check the visitor’s session for protected paths, and return context.redirect('/login/') or a 401 when they are not signed in. Make the protected pages render on demand with export const prerender = false.
Does Astro middleware run on static pages?
Only at build time. For prerendered pages, middleware runs once while the page is generated and never on visits, so it cannot enforce access. Protected pages must be on demand.
Can I protect a fully static Astro site?
Not with middleware alone. Use your host’s access controls, such as Cloudflare Access, Netlify or Vercel password protection, or put the site behind basic auth at the server level. See password-protecting an Astro site.
Should I redirect or return 401 for unauthenticated requests?
Redirect browsers requesting pages to the login page. Return 401 for API endpoints, because scripts calling them cannot follow a login page.