Code that runs before a request reaches its route, on every matching request.
A single middleware.ts file at the project root runs before a request completes routing, for every request that matches its configured matcher. It's the right place for logic that needs to happen before a page even starts rendering — redirects, rewrites, authentication gating, A/B test bucketing, or adding response headers uniformly across many routes.
Middleware runs exclusively on the Edge runtime, which means it inherits the same restricted API surface as any Edge function — no direct database connections through Node-specific drivers, no filesystem access. Because it sits on the hot path of every matching request, it needs to stay fast and lightweight; heavier logic, like a full auth check against a database, usually belongs in the actual route or a Route Handler, with Middleware handling only the cheap, request-level decision.
What you'll walk away knowing