What is Middleware?

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.

Middleware File Convention

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.

Matching Paths

Next.js Middleware gets invoked for every route in your project, following this execution order:

  1. Headers from next.config.js
  2. Redirects from next.config.js
  3. Middleware (rewrites, redirects, etc.)
  4. beforeFiles (rewrites) from next.config.js
  5. Filesystem routes (public/, _next/static/, pages/, app/, etc.)
  6. afterFiles (rewrites) from next.config.js
  7. Dynamic Routes (/blog/[slug])
  8. fallback (rewrites) from next.config.js

You have two ways to specify which paths Middleware will run on: custom matcher config and conditional statements.

Matcher