Consider middleware like a traffic cop standing in the middle of a busy intersection. The cop can direct the traffic (requests) to different paths or modify their course.
Middleware is executed even before cached content and routes are matched. Its primary job is to direct the flow of requests based on the incoming data.
To use Middleware, create a file named middleware.ts
(or middleware.js
) in the root of your project, i.e., at the same level as pages
or app
, or inside src
if you're using that directory structure.
Here's a basic example:
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
export const config = {
matcher: '/about/:path*',
}
In this example, the middleware function intercepts every request and redirects it to the /home
URL.
Next.js Middleware gets invoked for every route in your project, following this execution order:
next.config.js
next.config.js
beforeFiles
(rewrites) from next.config.js
public/
, _next/static/
, pages/
, app/
, etc.)afterFiles
(rewrites) from next.config.js
/blog/[slug]
)fallback
(rewrites) from next.config.js
You have two ways to specify which paths Middleware will run on: custom matcher config and conditional statements.