Definition

What is Middleware (Next.js)?

Code that runs before a request is completed, on every matching path. Used for auth checks, redirects, header rewriting, and A/B routing.

Next.js Middleware runs at the Edge before any page or API route handler. It sits at `middleware.ts` in the project root (or `src/`) and exports a default function that receives the request, can modify headers, rewrite to a different URL, redirect, or pass through. Common patterns: authentication gates (check a cookie, redirect to /login if missing), feature flags (rewrite to A or B variant), bot blocking (return 403 for User-Agent matches), geo-routing (rewrite to /us or /uk based on IP geo), and AB-test cookie planting. Middleware runs on the Edge Runtime, so the constraints there apply (no Node stdlib, ~1 MB bundle cap). Matchers in `config.matcher` limit which paths trigger middleware — set them carefully because every request to a matched path adds latency.

Learn more

Related terms

See it in action

Try InBuild free — no credit card required.