Bird
Raised Fist0
Astroframework~20 mins

Middleware for authentication in Astro - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Astro Middleware Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a user without a valid token accesses a protected route?

Consider this Astro middleware that checks for a valid authentication token before allowing access to a page.

export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization');
  if (!token || token !== 'valid-token') {
    return redirect('/login');
  }
  return new Response('Access granted');
}

What will the user see if they visit the protected page without a valid token?

Astro
export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization');
  if (!token || token !== 'valid-token') {
    return redirect('/login');
  }
  return new Response('Access granted');
}
AThe user is redirected to the /login page.
BThe user sees the message 'Access granted'.
CThe user gets a 500 Internal Server Error.
DThe user sees a blank page with no content.
Attempts:
2 left
💡 Hint

Think about what the redirect function does when the token is missing or invalid.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Astro middleware snippet

Review the following middleware code that should block unauthenticated users:

export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization')
  if (!token) {
    redirect('/login')
  }
  return new Response('Welcome!')
}

Which option correctly describes the syntax error?

Astro
export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization')
  if (!token) {
    redirect('/login')
  }
  return new Response('Welcome!')
}
AThe function must be named middleware, not onRequest.
BMissing semicolons cause a syntax error in Astro middleware.
CThe headers.get method is invalid and should be headers.getHeader.
DThe redirect call is missing a return statement, so the function continues instead of redirecting.
Attempts:
2 left
💡 Hint

Consider what happens after calling redirect without returning it.

🔧 Debug
advanced
2:00remaining
Why does this middleware fail to block unauthorized users?

Examine this middleware code:

export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization');
  if (token !== 'valid-token') {
    redirect('/login');
  }
  return new Response('Access granted');
}

Users without the valid token still see 'Access granted'. Why?

Astro
export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization');
  if (token !== 'valid-token') {
    redirect('/login');
  }
  return new Response('Access granted');
}
ABecause the token comparison uses !== instead of !=, causing a logic error.
BBecause the middleware must throw an error to block access, not redirect.
CBecause redirect is called but not returned, so the function continues and returns 'Access granted'.
DBecause request.headers.get returns a promise and needs await.
Attempts:
2 left
💡 Hint

Check what happens after calling redirect without returning it.

❓ state_output
advanced
2:00remaining
What is the response status code when middleware redirects a user?

Given this middleware snippet:

export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization');
  if (!token) {
    return redirect('/login');
  }
  return new Response('Welcome!');
}

What HTTP status code will the client receive if redirected?

Astro
export async function onRequest({ request, redirect }) {
  const token = request.headers.get('Authorization');
  if (!token) {
    return redirect('/login');
  }
  return new Response('Welcome!');
}
A301 Moved Permanently
B302 Found (Temporary Redirect)
C404 Not Found
D200 OK
Attempts:
2 left
💡 Hint

Redirects usually use status codes in the 3xx range. Which one is common for temporary redirects?

🧠 Conceptual
expert
2:00remaining
Why use middleware for authentication instead of checking inside each page?

In Astro, you can check authentication either inside each page component or centrally in middleware.

Which reason best explains why middleware is preferred for authentication?

AMiddleware runs before page rendering, so it can block unauthorized requests early and avoid unnecessary work.
BMiddleware allows you to write authentication logic in the page component itself, making code simpler.
CMiddleware automatically stores user sessions in cookies without extra code.
DMiddleware runs only on the client side, improving performance.
Attempts:
2 left
💡 Hint

Think about when middleware runs compared to page code.

Practice

(1/5)
1. What is the main purpose of middleware for authentication in Astro?
easy
A. To fetch data from an external API after the page loads
B. To style the webpage with CSS before rendering
C. To check if a user is allowed to access certain pages before loading them
D. To optimize images automatically during build

Solution

  1. Step 1: Understand middleware role

    Middleware runs before page loads to control access.
  2. Step 2: Identify authentication purpose

    Authentication middleware checks user identity to allow or block access.
  3. Final Answer:

    To check if a user is allowed to access certain pages before loading them -> Option C
  4. Quick Check:

    Middleware controls access = A [OK]
Hint: Middleware controls access before page loads [OK]
Common Mistakes:
  • Confusing middleware with styling or data fetching
  • Thinking middleware runs after page loads
  • Assuming middleware optimizes images
2. Which is the correct way to allow access to the next middleware or page in Astro authentication middleware?
easy
A. return context.stop()
B. return context.skip()
C. return context.block()
D. return context.next()

Solution

  1. Step 1: Recall middleware flow control

    In Astro, calling context.next() passes control to next middleware or page.
  2. Step 2: Identify correct method to continue

    Only context.next() allows access; others are invalid or block.
  3. Final Answer:

    return context.next() -> Option D
  4. Quick Check:

    Allow access = context.next() [OK]
Hint: Use context.next() to continue middleware chain [OK]
Common Mistakes:
  • Using non-existent methods like context.stop()
  • Confusing block and skip with next
  • Omitting return keyword
3. Given this Astro middleware code snippet, what happens if the user is not authenticated?
export async function middleware(context) {
  if (!context.cookies.get('authToken')) {
    return new Response('Unauthorized', { status: 401 });
  }
  return context.next();
}
medium
A. The user sees a 401 Unauthorized response and page does not load
B. The user is redirected to the homepage
C. The middleware ignores the check and loads the page
D. The user is logged out automatically

Solution

  1. Step 1: Analyze authentication check

    The code checks if 'authToken' cookie exists; if not, returns 401 response.
  2. Step 2: Understand middleware response effect

    Returning a Response with status 401 stops page loading and shows unauthorized message.
  3. Final Answer:

    The user sees a 401 Unauthorized response and page does not load -> Option A
  4. Quick Check:

    Missing authToken = 401 response [OK]
Hint: Return Response with 401 to block unauthorized users [OK]
Common Mistakes:
  • Assuming middleware redirects automatically
  • Thinking page loads despite 401 response
  • Confusing logout with blocking access
4. Identify the error in this Astro middleware code for authentication:
export async function middleware(context) {
  if (!context.cookies.get('authToken')) {
    context.next();
  }
  return new Response('Unauthorized', { status: 401 });
}
medium
A. The Response status 401 should be 200 to allow access
B. context.next() is called but its result is not returned, so middleware blocks all requests
C. The cookie name 'authToken' is incorrect and causes a runtime error
D. Middleware functions cannot be async in Astro

Solution

  1. Step 1: Check middleware flow control

    context.next() must be returned to continue; here it is called but not returned.
  2. Step 2: Understand effect of missing return

    Since return is after if-block, middleware always returns 401 response, blocking all requests.
  3. Final Answer:

    context.next() is called but its result is not returned, so middleware blocks all requests -> Option B
  4. Quick Check:

    Return context.next() to allow access [OK]
Hint: Always return context.next() to continue middleware chain [OK]
Common Mistakes:
  • Calling context.next() without return
  • Misunderstanding cookie name importance
  • Thinking async is disallowed in middleware
5. You want to protect multiple private routes in Astro using middleware. Which approach correctly applies authentication middleware only to URLs starting with /dashboard or /settings?
hard
A. Check if context.url.pathname starts with '/dashboard' or '/settings' and run auth check only then
B. Apply middleware globally and always block access regardless of URL
C. Use middleware only on the homepage '/' to protect all routes
D. Check if context.url.pathname ends with '/dashboard' or '/settings' to run auth

Solution

  1. Step 1: Understand route matching in middleware

    Middleware can check context.url.pathname to target specific routes.
  2. Step 2: Identify correct string method for prefix matching

    Using startsWith matches routes beginning with '/dashboard' or '/settings'.
  3. Step 3: Evaluate other options

    Blocking all routes or checking endsWith is incorrect for this purpose.
  4. Final Answer:

    Check if context.url.pathname starts with '/dashboard' or '/settings' and run auth check only then -> Option A
  5. Quick Check:

    Use startsWith for route prefix matching [OK]
Hint: Use startsWith to target route prefixes in middleware [OK]
Common Mistakes:
  • Blocking all routes instead of specific ones
  • Using endsWith instead of startsWith
  • Applying middleware only on homepage
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard