0
0
NextJSframework~10 mins

Middleware for API routes 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 the middleware function from Next.js.

NextJS
import { [1] } from 'next/server';
Drag options to blanks, or click blank then click option'
Amiddleware
BuseMiddleware
ChandleMiddleware
DapplyMiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Using default import instead of named import.
Using incorrect function names like useMiddleware.
2fill in blank
medium

Complete the code to define a middleware function that logs the request URL.

NextJS
export function middleware(request) {
  console.log(request.[1]);
  return new Response('OK');
}
Drag options to blanks, or click blank then click option'
Amethod
Burl
Cheaders
Dbody
Attempts:
3 left
💡 Hint
Common Mistakes
Using request.method instead of request.url.
Trying to access request.body which is not directly available.
3fill in blank
hard

Fix the error in the middleware to correctly forward the request to the next handler.

NextJS
export function middleware(request) {
  return [1](request);
}
Drag options to blanks, or click blank then click option'
AforwardRequest
Bnext()
ChandleRequest
Dfetch
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a non-existent function like next() or forwardRequest().
Not returning a Response object.
4fill in blank
hard

Complete the code to create a matcher that applies middleware only to API routes starting with '/api/'.

NextJS
export const config = {
  matcher: [1]
};
Drag options to blanks, or click blank then click option'
A'/api/:path*'
B'/((?!_next|api).*)'
C'/api'
D'/dashboard/:path*'
Attempts:
3 left
💡 Hint
Common Mistakes
Using exact path '/api' which doesn't match /api/users.
Using patterns that match non-API routes.
5fill in blank
hard

Fill all three blanks to create middleware that blocks requests without a valid token header.

NextJS
export function middleware(request) {
  const token = request.headers.get('[1]');
  if (!token || token !== '[2]') {
    return new Response('Unauthorized', { status: [3] });
  }
  return fetch(request);
}
Drag options to blanks, or click blank then click option'
AAuthorization
BX-Auth-Token
CBearer
D401
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong header names like Authorization when the token is in X-Auth-Token.
Returning wrong status codes like 403 instead of 401.