▲ Next.js Intermediate

What is the Next.js App Router middleware in depth?

Answer

Middleware in Next.js runs at the edge (globally distributed) before requests reach your pages or API routes. Understanding its capabilities and limitations is important: Edge Runtime constraints: middleware runs in the Edge Runtime, which is a subset of Node.js: no Node.js built-ins (fs, path, crypto), limited npm package support; but: full Web API support (fetch, URL, Request, Response, Headers, Cookies), fast startup time (no cold start like serverless). NextRequest extensions: beyond standard Request: request.nextUrl — parsed URL with Next.js-specific properties (pathname, searchParams, locale); request.geo — country, city, region (on Vercel); request.ip — client IP; request.cookies — cookie management. NextResponse extensions: NextResponse.redirect(url) — 307 redirect; NextResponse.rewrite(url) — rewrite URL without redirect (browser URL unchanged); NextResponse.next() — continue to next handler; response.cookies.set(name, value, options). Authentication pattern: verify session token → redirect to login if invalid. Geolocation-based routing: detect country from request.geo.country → redirect to locale. A/B testing: set a cookie to assign user to variant, rewrite to variant page. Rate limiting: use a Redis-backed counter (via fetch to a rate limit service — can't use Redis client directly in edge). matcher specificity: use specific matchers to avoid running on static assets: matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"].