Middleware runs before a route (often at the edge) and can redirect/rewrite (e.g., locale routing, auth gates). It should be lightweight and has runtime limitations compared to full Node.js (not all APIs are available).
Next.js Middleware runs *before* your route handler/page code and can execute at the edge. It’s ideal for request-level concerns that must happen early:
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(req: NextRequest) {
const loggedIn = Boolean(req.cookies.get('session'))
if (!loggedIn && req.nextUrl.pathname.startsWith('/admin')) {
const url = req.nextUrl.clone()
url.pathname = '/login'
return NextResponse.redirect(url)
}
return NextResponse.next()
}