middleware.ts

A single file at the project root that runs code before matching requests are routed, to redirect, rewrite, set headers or check sessions.

In more detail

It runs before cached pages are served, by default in the Edge runtime; Node.js runtime support became stable in Next.js 15.5. Keep it fast and use a matcher so it skips static files. Next.js 16 renamed it to proxy.ts.

Example

export function middleware(req: NextRequest) {
  if (!req.cookies.get('session')) return NextResponse.redirect(new URL('/login', req.url));
}

Related terms

Taught in

References