Complete the code to import the middleware function correctly.
import [1] from '../middleware/auth.js';
The middleware function is named authMiddleware and must be imported with the exact name to work properly.
Complete the code to apply middleware to a protected route.
export const get = async ({ request }) => {
await [1](request);
return new Response('Protected content');
};The middleware function authMiddleware is called to check authentication before returning protected content.
Fix the error in the middleware function to correctly block unauthorized users.
export async function authMiddleware(request) {
const user = await getUserFromRequest(request);
if (!user) {
return new Response('Unauthorized', { status: [1] });
}
}The HTTP status code 401 means unauthorized access and is the correct code to return when the user is not authenticated.
Fill both blanks to create a middleware that redirects unauthorized users to login.
export async function authMiddleware(request) {
const user = await getUserFromRequest(request);
if (!user) {
return new Response(null, { status: [1], headers: { Location: [2] } });
}
}Status code 302 is used for redirecting, and the Location header should point to the login page '/login'.
Fill all three blanks to create a protected route that uses middleware and returns user data.
import { authMiddleware } from '../middleware/auth.js'; export const get = async ({ request }) => { const user = await [1](request); if (!user) { return new Response(null, { status: [2], headers: { Location: [3] } }); } return new Response(JSON.stringify({ name: user.name }), { status: 200 }); };
The route calls authMiddleware to check the user. If no user, it redirects with status 302 to '/login'. Otherwise, it returns user data.
