0
0
NextJSframework~10 mins

Middleware.ts file convention 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 NextResponse object from the correct module.

NextJS
import { [1] } from 'next/server';
Drag options to blanks, or click blank then click option'
ANextMiddleware
BNextRequest
CNextResponse
DNextHandler
Attempts:
3 left
💡 Hint
Common Mistakes
Importing NextRequest instead of NextResponse
Using incorrect module names
Confusing middleware handler names
2fill in blank
medium

Complete the code to define a middleware function that receives a request.

NextJS
export function middleware([1]) {
  return NextResponse.next();
}
Drag options to blanks, or click blank then click option'
Arequest
Bcontext
Cresponse
Devent
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'response' as the parameter instead of 'request'
Using unrelated parameter names
3fill in blank
hard

Fix the error in the middleware export syntax.

NextJS
export function [1](request) {
  return NextResponse.next();
}
Drag options to blanks, or click blank then click option'
Amiddleware
BMiddleware
ChandleMiddleware
DnextMiddleware
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase or different function names
Exporting the function as default
4fill in blank
hard

Fill both blanks to create a matcher that applies middleware only to API routes.

NextJS
export const config = {
  matcher: [1] 
};

// Matches paths starting with [2]
Drag options to blanks, or click blank then click option'
A["/api/:path*"]
B"/api/*"
C["/app/:path*"]
D"/app/*"
Attempts:
3 left
💡 Hint
Common Mistakes
Using string instead of array for matcher
Using wrong path prefixes
5fill in blank
hard

Fill all three blanks to create middleware that redirects users from '/' to '/home'.

NextJS
import { NextResponse } from 'next/server';

export function middleware([1]) {
  if (request.nextUrl.pathname === [2]) {
    return NextResponse.redirect(new URL([3], request.url));
  }
  return NextResponse.next();
}
Drag options to blanks, or click blank then click option'
Arequest
B"/"
C"/home"
Dresponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong parameter names
Incorrect path strings
Not using NextResponse.redirect properly