What is middleware in Next.js, and when does it run?
Short answer
Middleware is a special function defined in a middleware.js file at the root of your project that runs before a request completes, letting you inspect, modify, redirect, or block requests before they reach your actual pages or API routes.
Advertisement
AModel answer
Middleware is a special function defined in a middleware.js file at the root of your project that runs before a request completes, letting you inspect, modify, redirect, or block requests before they reach your actual pages or API routes.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
console.log('Request received:', request.nextUrl.pathname);
return NextResponse.next();
}Real-world example
An application logs every incoming request's path using middleware, giving the team visibility into traffic patterns before any page even starts rendering.
Likely follow-ups
- Does middleware run on every single request by default?
- What is the difference between middleware and a route handler?
Related topics