Consider an Astro project with a middleware that checks user authentication before allowing access to a protected route.
What is the expected behavior if a user tries to access /dashboard without being logged in?
export async function onRequest({ request, redirect }) { const isAuthenticated = Boolean(request.headers.get('cookie')?.includes('session')); if (!isAuthenticated) { return redirect('/login'); } return new Response('Welcome to your dashboard'); }
Think about what the middleware does when authentication fails.
The middleware checks if the user has a session cookie. If not, it redirects the user to the login page to prevent unauthorized access.
Review the following Astro middleware code intended to protect a route by checking a token in cookies.
Which option correctly identifies the syntax error?
export async function onRequest({ request, redirect }) { const token = request.headers.get('cookie').match(/token=([^;]+)/)[1]; if (!token) { return redirect('/login'); } return new Response('Access granted'); }
Consider what happens if the cookie header is missing.
If request.headers.get('cookie') returns null, calling match on it causes a runtime error because null has no methods.
Given this Astro middleware protecting a route, what HTTP status code will the client receive when not authenticated?
export async function onRequest({ request, redirect }) { const isLoggedIn = request.headers.get('cookie')?.includes('auth=true'); if (!isLoggedIn) { return redirect('/login'); } return new Response('Protected content'); }
What does the redirect function do by default?
The redirect function sends a 302 status code by default, telling the browser to go to the login page.
Examine this middleware code. It is supposed to block access if the user is not authenticated, but it allows access anyway.
What is the cause?
export async function onRequest({ request, redirect }) { const cookie = request.headers.get('cookie'); if (cookie && cookie.includes('auth=true')) { return new Response('Access granted'); } // Missing return here return redirect('/login'); }
What happens if you call a function but do not return its result in middleware?
Without returning the redirect response, the middleware does not stop execution and does not send the redirect response to the client.
Choose the statement that best describes a key difference between Astro's middleware approach for protected routes and Express.js middleware.
Think about how Astro middleware handles requests compared to Express.
Astro middleware runs before page rendering and must return a response or redirect to control flow. Express middleware uses next() to pass control to the next middleware or route handler.
