What is Next.js middleware?
Code that runs at the edge before your route handlers, on every matching request. Used for auth checks, redirects, A/B routing, and header rewriting. The matcher pattern determines which routes the middleware covers — and where the canonical bug lives.
Full explanation
Next.js middleware is a single `middleware.ts` file at your project root. It exports a `middleware()` function and a `config` object with a `matcher`. The function runs at Vercel's edge (or your self-hosted edge) before the route handler. Matcher patterns determine which routes invoke the middleware: `/admin/:path*` matches `/admin/foo` but NOT `/api/admin/foo` — and that exact mismatch is the most-shipped bug in AI-generated middleware. Additionally: middleware below Next.js 15.2.3 (or 14.2.25, 13.5.9, 12.3.5) is vulnerable to CVE-2025-29927 — a critical bypass via the `x-middleware-subrequest` HTTP header that lets an unauthenticated attacker skip middleware entirely.
Example
AI-generated middleware: `export const config = { matcher: '/admin/:path*' };` plus an auth-check function. Looks correct. But your protected admin routes are at `/api/admin/users` — the matcher does not match. Middleware never runs on the routes it was supposed to protect. Test: `curl https://your-app/api/admin/users` from an unauthenticated context — should return 401/403/redirect; if it returns the data, your matcher missed.
Related
FAQ
Should I trust middleware as my only auth layer?
No — defense in depth. Middleware catches unauthenticated requests at the edge (faster, cheaper); the route handler ALSO checks auth so a middleware regression (matcher typo, CVE-2025-29927-style bypass, Vercel deployment glitch) does not become a data breach. Both layers; both required.
Does middleware run on Server Actions?
Yes — Server Action requests pass through middleware. The matcher needs to include the Next.js Server Action endpoint (which is the page route the action is associated with, not a separate URL). Verify with curl that a matching request actually reaches the middleware function.