Performance: Protected routes and middleware
This concept affects page load speed and interaction responsiveness by controlling when and how protected content is rendered or blocked.
export async function middleware({ request, redirect }, next) { const user = await fetchUserFromRequest(request); if (!user) { return redirect('/login'); } return next(); } export async function get() { return { status: 200, body: await getProtectedContent() }; }
export async function get() { const user = await fetchUser(); if (!user) { return { status: 302, headers: { Location: '/login' } }; } const body = await getProtectedContent(); return { status: 200, body: body }; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Loading protected content before auth check | High (loads full DOM) | Multiple (full page reflow) | High (renders unauthorized content) | [X] Bad |
| Middleware redirects unauthorized early | Low (no DOM for unauthorized) | None (no reflow) | Low (no paint for unauthorized) | [OK] Good |
/dashboard in Astro?/profile without a valid token?export const matcher = ['/profile'];
export async function middleware({ request, redirect }) {
const token = request.headers.get('authorization');
if (!token) {
return redirect('/login');
}
return;
}/admin routes:export const matcher = '/admin/*';
export function middleware({ request, redirect }) {
const user = request.headers.get('user');
if (user !== 'admin') {
redirect('/not-authorized');
}
}/dashboard and /settings routes using middleware in Astro. Which matcher setup correctly protects both paths and their subpaths?Pass the test and this pattern moves unknown