Loading
Code that runs before a page loads, checking things like whether a user is logged in — like a bouncer at the door who checks IDs before letting people into the club.
A function exported from middleware.ts at the project root that runs before every matched request. It can rewrite URLs, redirect, set headers, or modify cookies. Middleware runs at the edge and executes before any page or API route.
Next.js middleware executes in the Edge Runtime (V8 isolates, no Node.js APIs) before the routing layer resolves a request. It receives NextRequest and must return NextResponse (or NextResponse.next() to continue). The matcher config constrains execution to specific paths. Middleware cannot access the file system, dynamic imports, or Node.js built-ins unless the Node.js runtime is explicitly configured.