Complete the code to import the middleware function correctly.
import [1] from 'astro/middleware';
The middleware function is imported as middleware from 'astro/middleware'.
Complete the code to check if the user is authenticated inside the middleware.
export const onRequest = middleware(async ({ request, next }) => {
if (!request.cookies.get('[1]')) {
return new Response('Unauthorized', { status: 401 });
}
return next();
});The middleware checks for the presence of the auth_token cookie to verify authentication.
Fix the error in the middleware function to correctly call the next handler.
export const onRequest = middleware(async ({ request, next }) => {
if (!request.cookies.get('auth_token')) {
return new Response('Unauthorized', { status: 401 });
}
return [1];
});The next function is asynchronous and must be called with parentheses and awaited: await next().
Fill both blanks to create a middleware that redirects unauthenticated users to the login page.
export const onRequest = middleware(async ({ request, next }) => {
if (!request.cookies.get([1])) {
return new Response(null, {
status: 302,
headers: { Location: [2] }
});
}
return await next();
});The middleware checks for the 'auth_token' cookie and redirects to '/login' if missing.
Fill all three blanks to create middleware that logs the request method, checks authentication, and proceeds.
export const onRequest = middleware(async ({ request, next }) => {
console.log('Request method:', [1]);
if (!request.cookies.get([2])) {
return new Response('Unauthorized', { status: 401 });
}
return await [3];
});The middleware logs request.method, checks for 'auth_token' cookie, and calls next() to continue.
