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
matcherto 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
- How does data fetching work in the App Router?
- How did caching defaults change in Next.js 15?
- What happens, step by step, when a request reaches a Next.js App Router application?
- What is Next.js and what problems does it solve on top of React?
- What are the differences between the App Router and the Pages Router?
- What is the difference between Server Components and Client Components?
- Explain the App Router file conventions: page, layout, loading, error, not-found, template and route.
- Explain SSR, SSG, ISR and CSR in Next.js.