0
0
NextJSframework~10 mins

Protected routes with middleware in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import NextResponse from Next.js.

NextJS
import { [1] } from 'next/server';
Drag options to blanks, or click blank then click option'
AuseMiddleware
BwithAuth
ChandleRequest
DNextResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent import name like 'useMiddleware'.
Trying to import default instead of named export.
2fill in blank
medium

Complete the code to check if the user is authenticated inside the middleware.

NextJS
export function middleware(request) {
  const token = request.cookies.get('[1]');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}
Drag options to blanks, or click blank then click option'
Atoken
Bauth_token
Cuser_token
Dsession_id
Attempts:
3 left
💡 Hint
Common Mistakes
Using a cookie name that does not exist in the app.
Confusing session_id with token.
3fill in blank
hard

Fix the error in the middleware to correctly redirect unauthenticated users.

NextJS
if (!token) {
  return [1](new URL('/login', request.url));
}
Drag options to blanks, or click blank then click option'
ANextResponse.redirect
BredirectResponse
Cres.redirect
Dredirect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'redirect' as a function without NextResponse prefix.
Using Express style 'res.redirect' which does not exist here.
4fill in blank
hard

Fill both blanks to allow middleware only on protected routes and exclude public ones.

NextJS
export const config = {
  matcher: ['/dashboard[1]', '/settings[2]']
};
Drag options to blanks, or click blank then click option'
A/*
B/public
C/api
D/login
Attempts:
3 left
💡 Hint
Common Mistakes
Using exact paths without wildcards, missing nested routes.
Including public paths in matcher causing unwanted middleware runs.
5fill in blank
hard

Fill all three blanks to extract the token, check it, and redirect if missing.

NextJS
export function middleware(request) {
  const token = request.cookies.get([1]);
  if (!token) {
    return NextResponse.[2](new URL([3], request.url));
  }
}
Drag options to blanks, or click blank then click option'
A'token'
B'/login'
Credirect
DNextResponse.redirect
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting quotes around cookie name or URL path.
Using incorrect method names for redirect.