Next.js
Middleware
Middleware runs before a request is completed. It executes on the Edge Runtime and can rewrite, redirect, and protect routes.
Basics
- File at project root:
middleware.js. - Runs before routes, RSC rendering, and Route Handlers.
- Edge-only; no Node APIs.
import { NextResponse } from "next/server";
export function middleware(request) {
return NextResponse.next();
}Use cases
- Auth checks and redirects.
if (!isAuthenticated) return NextResponse.redirect(new URL("/login", request.url));- Rewrites/redirects, i18n routing, feature flags, A/B tests.
- Page protection and bot blocking.
Matcher
export const config = { matcher: ["/dashboard/:path*"] };Limitations
- No direct DB access, no Node APIs, no server-only libraries.