Middleware for authentication helps check who you are before letting you use parts of a website. It keeps things safe by stopping strangers from getting in.
Middleware for authentication in Astro
export async function onRequest(context, next) { // check user authentication here if (!context.request.headers.get('Authorization')) { return new Response('Unauthorized', { status: 401 }); } return next(); }
The onRequest function runs before your page or API loads.
Use next() to continue if the user is allowed.
export async function onRequest(context, next) { const token = context.request.headers.get('Authorization'); if (!token) { return new Response('Unauthorized', { status: 401 }); } return next(); }
export async function onRequest(context, next) { const url = new URL(context.request.url); if (url.pathname.startsWith('/private')) { const token = context.request.headers.get('Authorization'); if (!token) { return new Response('Unauthorized', { status: 401 }); } } return next(); }
This middleware checks if the user tries to visit '/dashboard'. If they don't send an Authorization token, it stops them with a 401 message. Otherwise, it lets them continue.
export async function onRequest(context, next) { const url = new URL(context.request.url); if (url.pathname.startsWith('/dashboard')) { const token = context.request.headers.get('Authorization'); if (!token) { return new Response('Unauthorized - Please login', { status: 401 }); } } return next(); } // This middleware blocks access to '/dashboard' if no Authorization header is sent.
Middleware runs on every request, so keep it fast and simple.
Use clear messages and status codes like 401 for unauthorized access.
Remember to test your middleware by trying to access protected pages with and without login.
Middleware checks user identity before loading pages.
It helps protect private parts of your site.
Use next() to allow access, or return a response to block.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before page loads to control access.Step 2: Identify authentication purpose
Authentication middleware checks user identity to allow or block access.Final Answer:
To check if a user is allowed to access certain pages before loading them -> Option CQuick Check:
Middleware controls access = A [OK]
- Confusing middleware with styling or data fetching
- Thinking middleware runs after page loads
- Assuming middleware optimizes images
Solution
Step 1: Recall middleware flow control
In Astro, callingcontext.next()passes control to next middleware or page.Step 2: Identify correct method to continue
Onlycontext.next()allows access; others are invalid or block.Final Answer:
return context.next() -> Option DQuick Check:
Allow access = context.next() [OK]
- Using non-existent methods like context.stop()
- Confusing block and skip with next
- Omitting return keyword
export async function middleware(context) {
if (!context.cookies.get('authToken')) {
return new Response('Unauthorized', { status: 401 });
}
return context.next();
}Solution
Step 1: Analyze authentication check
The code checks if 'authToken' cookie exists; if not, returns 401 response.Step 2: Understand middleware response effect
Returning a Response with status 401 stops page loading and shows unauthorized message.Final Answer:
The user sees a 401 Unauthorized response and page does not load -> Option AQuick Check:
Missing authToken = 401 response [OK]
- Assuming middleware redirects automatically
- Thinking page loads despite 401 response
- Confusing logout with blocking access
export async function middleware(context) {
if (!context.cookies.get('authToken')) {
context.next();
}
return new Response('Unauthorized', { status: 401 });
}Solution
Step 1: Check middleware flow control
context.next() must be returned to continue; here it is called but not returned.Step 2: Understand effect of missing return
Since return is after if-block, middleware always returns 401 response, blocking all requests.Final Answer:
context.next() is called but its result is not returned, so middleware blocks all requests -> Option BQuick Check:
Return context.next() to allow access [OK]
- Calling context.next() without return
- Misunderstanding cookie name importance
- Thinking async is disallowed in middleware
/dashboard or /settings?Solution
Step 1: Understand route matching in middleware
Middleware can checkcontext.url.pathnameto target specific routes.Step 2: Identify correct string method for prefix matching
UsingstartsWithmatches routes beginning with '/dashboard' or '/settings'.Step 3: Evaluate other options
Blocking all routes or checking endsWith is incorrect for this purpose.Final Answer:
Check if context.url.pathname starts with '/dashboard' or '/settings' and run auth check only then -> Option AQuick Check:
Use startsWith for route prefix matching [OK]
- Blocking all routes instead of specific ones
- Using endsWith instead of startsWith
- Applying middleware only on homepage
Ready to prove it?
Pass the test and this pattern moves unknown
