Next.js Hard technical 1 views 1 min read

How to use middleware in Next.js API routes?

Peer-reviewed by HireXTech Technical Panel • Updated for 2025/2026 hiring • Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Next.js conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

In Next.js, you can use middleware to run code before your API route handlers. Middleware can be used for tasks like authentication, logging, or modifying requests and responses.

Example of using middleware for authentication:

// app/api/middleware/auth.js
export async function authMiddleware(request) {
  const token = request.headers.get("Authorization");

  if (!token || token !== "your-secret-token") {
    return new Response(JSON.stringify({ error: "Unauthorized" }), {
      status: 401,
      headers: { "Content-Type": "application/json" },
    });
  }

  return null; // No error, proceed to the next handler
}

You can then use this middleware in your API route:

// app/api/protected/route.js
import { authMiddleware } from "../middleware/auth";

export async function GET(request) {
  const authError = await authMiddleware(request);
  if (authError) {
    return authError; // Return the error response if unauthorized
  }

  const data = await getProtectedData();
  return new Response(JSON.stringify(data), {
    headers: { "Content-Type": "application/json" },
  });
}

In this example, the authMiddleware checks for a valid authorization token before allowing access to the protected API route. If the token is invalid or missing, it returns a 401 Unauthorized response.

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?