▲ Next.js Beginner

What is Next.js middleware?

Answer

Next.js middleware runs before a request is completed — it intercepts requests and can rewrite, redirect, add headers, or send a response before the request reaches the page or API route. Middleware runs at the Edge (closest server to the user) for minimal latency. Creating middleware: create a middleware.ts file in the project root (or src/): import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; export function middleware(request: NextRequest) { const token = request.cookies.get("auth-token"); if (!token && request.nextUrl.pathname.startsWith("/dashboard")) { return NextResponse.redirect(new URL("/login", request.url)); } const response = NextResponse.next(); response.headers.set("x-custom-header", "custom-value"); return response; } export const config = { matcher: ["/dashboard/:path*", "/api/protected/:path*"] };. Middleware capabilities: read/write cookies (request.cookies, response.cookies); read request headers; redirect (NextResponse.redirect()); rewrite URL (NextResponse.rewrite()); return response early (NextResponse.json()); add/modify response headers. Matcher config: specify which paths the middleware runs on (regex patterns supported). Without matcher, runs on ALL routes (expensive). Edge runtime: middleware runs on the Edge Runtime — faster, global distribution, but limited APIs (no Node.js built-ins like fs). Use cases: authentication/authorization, i18n routing, A/B testing, bot detection, rate limiting, logging, geo-based routing.