Next.js Medium technical 0 views 1 min read

What is Next.js middleware and when should you use it?

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

Middleware in middleware.ts at the project root runs before a request is completed, on the Edge runtime, and can rewrite, redirect, set headers or return a response directly. It is matched with a matcher config or conditional logic.

export function middleware(req: NextRequest) {
  if (!req.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
}
export const config = { matcher: ['/dashboard/:path*'] };

Common uses are auth gating, A/B testing via rewrites, locale detection, bot filtering and security headers. Constraints: it runs on every matched request, so keep it fast and avoid large dependencies. It cannot use Node APIs or query a database directly on the Edge runtime, and it is not a substitute for authorising data access inside routes.

Because middleware runs before caching, rewrites can change which cached page is served. Use it for coarse redirects and header logic, not data fetching.

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?