How to use middleware in Next.js API routes?
Assesses fundamental understanding of Next.js conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
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
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.