Next.js Developer interview question · Most asked

What is Next.js middleware (renamed `proxy` in Next.js 16) and what should it be used for?

Summary

Middleware (middleware.ts, called proxy.ts from Next.js 16) runs before a request is matched to a route, so it can rewrite, redirect, set headers/cookies or return early. It's good for lightweight concerns like locale redirects, A/B rewrites, and coarse auth redirects.

Longer Answer

It runs for every matched request, so keep it fast and limit it with config.matcher. Don't rely on it as the only authorization layer: check auth again in Server Components, Server Actions and Route Handlers close to the data. A 2025 vulnerability (CVE-2025-29927) let attackers bypass middleware via a crafted internal header, which shows why defense in depth matters.

Code Example

// middleware.ts (proxy.ts in Next.js 16)
import { NextResponse, type NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const hasSession = req.cookies.has("session");
  if (!hasSession && req.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ["/dashboard/:path*"] };

Key Points

  • Runs before routing; rewrite/redirect/headers
  • Use matcher to scope it
  • Keep it fast and light
  • Not the only auth check (defense in depth)

Deep dive: Request Lifecycle course: Next.js: Proxy (Middleware), Rendering and Caching

More most-asked Next.js Developer questions

← All Next.js Developer questions