Middleware in Next.js runs before every matched request. It's the right place for authentication checks, redirects, and route protection — logic that needs to run consistently regardless of which page hits first.

Here's the production-ready pattern for middleware auth in App Router, including the edge cases that catch most implementations off-guard. The same approach runs in production at pixova.io/blog/free-ai-background-generator.

What Middleware Can and Can't Do

Middleware runs at the edge — fast, close to users, before server or database hits. That speed comes with constraints.

Can do: Read/write cookies, read request headers, redirect requests, rewrite URLs, return early responses.