Q18: What is Next.js Middleware and where does it execute?
Middleware (middleware.js in root) runs before a request is completed, directly at the Edge network layer (before hitting cache or route handlers). Commonly used for authentication checks, URL redirects, header modifications, and bot detection.
Auth Redirect Middleware
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('token');
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*'],
};💡 Intercepts request routes to /dashboard, redirecting unauthenticated users to /login.
Key Takeaways
- Executes at the Edge network layer before matching routes.
- Uses config matcher arrays to target specific request paths.
Knowledge Check
Where does Next.js Middleware execute relative to route handlers and page rendering?