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
- matcher (middleware) — The config.matcher option exported from middleware.ts that lists which paths the middleware runs on.
- Edge runtime — A lightweight Next.js runtime based on V8 isolates and standard Web APIs, which starts almost instantly but cannot use most Node.js APIs.
- NextResponse — Next.js' extension of the Web Response object, with helpers for JSON responses, cookies, redirects and rewrites.
- authentication — Establishing who a request represents, for example by checking a password, a session cookie or a signed token.
Taught in
- Revalidation Strategies: revalidatePath & Cache Life — Next.js 15 & Modern App Router Architecture
- Streaming Endpoints: Server-Sent Events & NDJSON Feeds — Next.js 15 & Modern App Router Architecture
- Edge Middleware: Auth Verification & Route Matchers — Next.js 15 & Modern App Router Architecture
- Session Management: Secure Cookies & Token Validation — Next.js 15 & Modern App Router Architecture