Bird
Raised Fist0
NextJSframework~5 mins

Middleware for API routes in NextJS - Cheat Sheet & Quick Revision

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
Recall & Review
beginner
What is middleware in Next.js API routes?
Middleware is a function that runs before the main API route handler. It can modify the request or response, or stop the request from continuing.
Click to reveal answer
beginner
How do you apply middleware to a Next.js API route?
You create a middleware function and call it inside your API route handler before your main logic. You can also compose multiple middleware functions.
Click to reveal answer
beginner
What is a common use case for middleware in API routes?
Middleware is often used for tasks like checking user authentication, validating data, or logging requests before the main API logic runs.
Click to reveal answer
intermediate
How can middleware stop an API request from continuing?
Middleware can send a response early (like an error or redirect) and not call the next handler, which stops the request from reaching the main API logic.
Click to reveal answer
intermediate
Why is middleware helpful for code reuse in Next.js API routes?
Middleware lets you write common logic once and use it in many API routes, so you don’t repeat code and keep your routes clean.
Click to reveal answer
What does middleware in Next.js API routes do?
ARuns before the main API handler to process requests
BRuns after the API response is sent
COnly handles errors in API routes
DReplaces the API route handler completely
How can middleware stop an API request from continuing?
ABy calling the next handler
BBy throwing an error without response
CBy modifying the request body
DBy sending a response early and not calling next
Which is NOT a typical use of middleware in Next.js API routes?
AAuthentication checks
BRendering React components
CLogging requests
DData validation
How do you add middleware to a Next.js API route?
ABy importing and calling it inside the API handler
BBy adding it to next.config.js
CBy naming the file middleware.js
DBy using a special middleware keyword in the route
Why use middleware for common logic in API routes?
ATo slow down API responses
BTo repeat code in every route
CTo keep routes clean and reuse code
DTo avoid using API routes
Explain how middleware works in Next.js API routes and give an example use case.
Think about what happens before your API code runs.
You got /4 concepts.
    Describe how you would add middleware to a Next.js API route and why it is useful.
    Focus on the steps and benefits.
    You got /4 concepts.

      Practice

      (1/5)
      1. What is the main purpose of middleware in Next.js API routes?
      easy
      A. To run code before the API route handles a request
      B. To replace the API route handler completely
      C. To style the API response
      D. To store data permanently on the server

      Solution

      1. Step 1: Understand middleware role

        Middleware runs before the API route handler to process requests.
      2. Step 2: Identify correct purpose

        It can check, block, or modify requests but does not replace handlers or style responses.
      3. Final Answer:

        To run code before the API route handles a request -> Option A
      4. Quick Check:

        Middleware runs before API handler [OK]
      Hint: Middleware runs before API handler to control requests [OK]
      Common Mistakes:
      • Thinking middleware replaces the API handler
      • Confusing middleware with styling or storage
      • Assuming middleware runs after the API handler
      2. Which of the following is the correct way to continue to the API route handler inside Next.js middleware?
      easy
      A. return NextResponse.stop()
      B. return NextResponse.redirect()
      C. return NextResponse.next()
      D. return NextResponse.error()

      Solution

      1. Step 1: Recall Next.js middleware continuation method

        To continue processing the request, middleware must call NextResponse.next().
      2. Step 2: Match correct method

        NextResponse.stop() halts, redirect() sends elsewhere, error() signals failure.
      3. Final Answer:

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

        Use NextResponse.next() to continue [OK]
      Hint: Use NextResponse.next() to proceed to API handler [OK]
      Common Mistakes:
      • Using NextResponse.stop() which blocks the request
      • Confusing redirect() with continuing
      • Forgetting to return NextResponse.next()
      3. Given this middleware code, what will happen when a request with header x-auth: secret is sent?
      import { NextResponse } from 'next/server';
      
      export function middleware(request) {
        if (request.headers.get('x-auth') !== 'secret') {
          return NextResponse.redirect(new URL('/unauthorized', request.url));
        }
        return NextResponse.next();
      }
      medium
      A. The request is redirected to /unauthorized
      B. The request continues to the API route handler
      C. The middleware throws an error
      D. The request is blocked with no response

      Solution

      1. Step 1: Check header condition

        The middleware checks if 'x-auth' header equals 'secret'. If yes, it continues.
      2. Step 2: Analyze given header

        The request has 'x-auth: secret', so condition is false and middleware returns NextResponse.next().
      3. Final Answer:

        The request continues to the API route handler -> Option B
      4. Quick Check:

        Header matches 'secret' so continue [OK]
      Hint: Check header value to decide redirect or continue [OK]
      Common Mistakes:
      • Assuming redirect happens even if header matches
      • Thinking middleware throws error on mismatch
      • Ignoring header case sensitivity
      4. Identify the error in this Next.js middleware code:
      import { NextResponse } from 'next/server';
      
      export function middleware(request) {
        if (!request.headers.get('authorization')) {
          NextResponse.redirect('/login');
        }
        return NextResponse.next();
      }
      medium
      A. Using 'authorization' header instead of 'auth'
      B. Middleware function must be async
      C. NextResponse.next() should be inside the if block
      D. Missing return before NextResponse.redirect

      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 D
      4. Quick Check:

        Always return redirect response [OK]
      Hint: Always return redirect to stop middleware flow [OK]
      Common Mistakes:
      • Not returning redirect response
      • Thinking middleware must be async
      • Misplacing NextResponse.next() inside if block
      5. You want to create middleware that blocks requests to API routes if the query parameter token is missing or empty. Which code correctly implements this behavior?
      hard
      A. export function middleware(request) { const url = new URL(request.url); if (!url.searchParams.get('token')) { return NextResponse.redirect(new URL('/error', request.url)); } return NextResponse.next(); }
      B. export function middleware(request) { if (!request.query.token) { return NextResponse.redirect('/error'); } return NextResponse.next(); }
      C. export function middleware(request) { if (request.url.token === '') { return NextResponse.next(); } return NextResponse.redirect('/error'); }
      D. export function middleware(request) { const token = request.headers.get('token'); if (!token) { return NextResponse.next(); } return NextResponse.redirect('/error'); }

      Solution

      1. Step 1: Access query parameters correctly

        Use new URL(request.url) and url.searchParams.get('token') to read query params.
      2. Step 2: Check token presence and redirect if missing

        If token is missing or empty, redirect to /error; otherwise continue with NextResponse.next().
      3. Final Answer:

        Code that checks query param and redirects if missing -> Option A
      4. Quick Check:

        Use URL and searchParams for query checks [OK]
      Hint: Use URL and searchParams to check query tokens [OK]
      Common Mistakes:
      • Trying to access query params directly on request
      • Checking headers instead of query parameters
      • Reversing redirect and continue logic