Next.js Middleware: Interview Guide
N نکست.جی‌اس

Next.js Middleware: Interview Guide

Run code at the edge before requests complete — auth, redirects, geolocation, and A/B tests.

BugCast Admin··۵ دقیقه مطالعه

Middleware runs before a request is completed, letting you rewrite, redirect, or modify headers. It is a common senior Next.js interview topic.

Common Interview Questions

Q: Where does middleware live?

Answer: Place middleware.ts at root or inside src/. Use matcher to limit which paths run middleware — important for performance.


// middleware.ts at project root (or src/)
export function middleware(request) {
  return NextResponse.next();
}
export const config = { matcher: ["/dashboard/:path*"] };

Q: Middleware vs API route?

Answer: Middleware runs on Edge before routing completes — ideal for auth gates and redirects. API routes handle full request/response logic with Node or Edge runtime.

Q: Auth check pattern?

Answer: Read cookies/headers, redirect unauthenticated users, optionally set request headers for downstream Server Components.


const token = request.cookies.get("session");
if (!token) {
  return NextResponse.redirect(new URL("/login", request.url));
}

Q: Limitations?

Answer: Cannot access full Node APIs on Edge runtime. Keep middleware fast — heavy work belongs in Server Components or route handlers.

Key Points for Interviews

  • Runs before request hits page or API

  • Edge runtime by default — lightweight APIs only

  • Use matcher to avoid running on static assets

  • NextResponse.rewrite for internal rewrites

  • Pair with cookies/JWT for auth at the edge

#middleware#edge#interview

مطالب مرتبط