Bird
Raised Fist0
NextJSframework~20 mins

Why middleware intercepts requests in NextJS - Challenge Your Understanding

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why does Next.js middleware intercept requests?

In Next.js, middleware runs before a request reaches a page or API route. What is the main reason middleware intercepts requests?

ATo delay the request processing until the user confirms an action
BTo modify the request or response, like redirecting or adding headers, before reaching the final handler
CTo automatically cache all requests on the client side
DTo convert all requests into static HTML pages
Attempts:
2 left
💡 Hint

Think about what middleware can do before the page or API handles the request.

component_behavior
intermediate
2:00remaining
What happens when middleware redirects a request?

Consider this Next.js middleware snippet that redirects users based on a condition. What will the user see if the condition is true?

export function middleware(request) {
  if (!request.cookies.get('token')) {
    return Response.redirect(new URL('/login', request.url))
  }
  return Response.next()
}
AThe user is sent to the /login page before the original page loads
BThe user sees the original page but with a warning message
CThe middleware blocks the request and shows a blank page
DThe user stays on the original page but the URL changes to /login
Attempts:
2 left
💡 Hint

Redirect means sending the user to a different page before loading the original one.

state_output
advanced
2:00remaining
What is the output of this middleware modifying headers?

Given this middleware code, what header will the final response include?

export function middleware(request) {
  const response = Response.next()
  response.headers.set('X-Custom-Header', 'HelloWorld')
  return response
}
AThe response will not include any custom headers
BThe code will throw a runtime error because headers cannot be set this way
CThe response will include the header 'X-Custom-Header' with value 'HelloWorld'
DThe response will include 'X-Custom-Header' but with an empty value
Attempts:
2 left
💡 Hint

Think about how middleware can add headers to responses.

📝 Syntax
advanced
2:00remaining
Identify the syntax error in this middleware code

Which option correctly fixes the syntax error in this Next.js middleware?

export function middleware(request) {
  if request.cookies.get('user') {
    return Response.next()
  }
  return Response.redirect('/login')
}
AAdd a semicolon after the if statement condition
BChange 'if' to 'when' to fix the syntax
CRemove the curly braces after if statement
DAdd parentheses around the if condition: if (request.cookies.get('user')) { ... }
Attempts:
2 left
💡 Hint

JavaScript requires parentheses around conditions in if statements.

🔧 Debug
expert
3:00remaining
Why does this middleware cause a runtime error?

Examine this middleware code. Why does it cause a runtime error?

export function middleware(request) {
  if (!request.cookies.get('session')) {
    return Response.redirect('/signin')
  }
  const response = Response.next()
  response.headers.append('Set-Cookie', 'visited=true')
  return response
}
AResponse.next() returns a Response object whose headers are immutable, so append() causes an error
BThe redirect URL '/signin' is invalid and causes the error
Crequest.cookies.get() is not a function and causes a TypeError
DThe middleware must always return a string, not a Response object
Attempts:
2 left
💡 Hint

Consider if the headers of the Response object can be changed after Response.next()

Practice

(1/5)
1. What is the main reason Next.js middleware intercepts requests?
easy
A. To render React components on the server
B. To directly update the database
C. To check or modify requests before they reach the app
D. To compile CSS styles

Solution

  1. Step 1: Understand middleware role

    Middleware runs before the app processes requests, allowing inspection or modification.
  2. Step 2: Identify middleware purpose

    It is used for tasks like login checks, redirects, or adding headers before the app handles the request.
  3. Final Answer:

    To check or modify requests before they reach the app -> Option C
  4. Quick Check:

    Middleware intercepts requests = B [OK]
Hint: Middleware runs before app handles requests [OK]
Common Mistakes:
  • Thinking middleware renders UI components
  • Assuming middleware updates databases directly
  • Confusing middleware with CSS compilation
2. Which of the following is the correct way to continue request processing in Next.js middleware?
easy
A. return NextResponse.next()
B. return fetch()
C. return res.send()
D. return render()

Solution

  1. Step 1: Identify continuation method

    Next.js middleware uses NextResponse.next() to continue processing the request.
  2. Step 2: Eliminate incorrect options

    fetch() is for network calls, res.send() is Express.js syntax, render() is unrelated here.
  3. Final Answer:

    return NextResponse.next() -> Option A
  4. Quick Check:

    Continue middleware with NextResponse.next() = D [OK]
Hint: Use NextResponse.next() to continue middleware [OK]
Common Mistakes:
  • Using Express.js methods like res.send()
  • Trying to fetch inside middleware to continue
  • Calling render() which is not middleware syntax
3. Given this middleware code snippet, what happens when a request to '/dashboard' is made?
import { NextResponse } from 'next/server';
export function middleware(request) {
  if (!request.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
medium
A. The user is redirected to '/login' if no token cookie is found
B. The request is blocked with an error
C. The request proceeds without any check
D. The middleware crashes due to syntax error

Solution

  1. Step 1: Analyze cookie check

    The middleware checks if the 'token' cookie exists in the request.
  2. Step 2: Determine behavior based on cookie

    If no token cookie, it redirects to '/login'; otherwise, it continues processing.
  3. Final Answer:

    The user is redirected to '/login' if no token cookie is found -> Option A
  4. Quick Check:

    Missing token cookie triggers redirect = A [OK]
Hint: Check cookie presence to decide redirect or continue [OK]
Common Mistakes:
  • Assuming request is blocked instead of redirected
  • Thinking middleware crashes due to syntax
  • Ignoring cookie check and assuming request proceeds
4. Identify the error in this Next.js middleware code:
import { NextResponse } from 'next/server';
export function middleware(request) {
  if (request.nextUrl.pathname === '/admin') {
    NextResponse.redirect('/login');
  }
  return NextResponse.next();
}
medium
A. Incorrect import statement for NextResponse
B. Missing return before NextResponse.redirect()
C. Using request.nextUrl.pathname instead of request.url
D. NextResponse.next() should not be called

Solution

  1. Step 1: Check redirect usage

    NextResponse.redirect() must be returned to stop further processing.
  2. Step 2: Identify missing return

    The code calls NextResponse.redirect() but does not return it, so middleware continues incorrectly.
  3. Final Answer:

    Missing return before NextResponse.redirect() -> Option B
  4. Quick Check:

    Always return redirect response in middleware = A [OK]
Hint: Always return redirect response in middleware [OK]
Common Mistakes:
  • Forgetting to return redirect response
  • Confusing request.nextUrl with request.url
  • Thinking NextResponse.next() is disallowed
5. You want to use Next.js middleware to block access to '/secret' unless a user has a valid 'auth' cookie. Which approach correctly applies this logic and continues processing other requests normally?
hard
A. Throw an error if 'auth' cookie is missing
B. Always return NextResponse.next() without checking cookies
C. Modify the request URL directly without returning a response
D. Return NextResponse.redirect('/login') if no 'auth' cookie; else return NextResponse.next()

Solution

  1. Step 1: Define blocking condition

    Check if the 'auth' cookie exists when the request is for '/secret'.
  2. Step 2: Apply redirect or continue

    If no cookie, return a redirect response to '/login'; otherwise, call NextResponse.next() to continue.
  3. Final Answer:

    Return NextResponse.redirect('/login') if no 'auth' cookie; else return NextResponse.next() -> Option D
  4. Quick Check:

    Redirect missing auth, else continue = C [OK]
Hint: Redirect missing auth cookie, else continue with NextResponse.next() [OK]
Common Mistakes:
  • Not returning redirect response
  • Throwing errors instead of redirecting
  • Modifying request without returning response