Skip to main content
Middleware runs before a request is completed. It can inspect the incoming request and respond by redirecting, rewriting, setting headers, or modifying cookies.
middleware.ts

Convention

Create a middleware.ts (or middleware.js) file in the root of your project (at the same level as app/ or pages/). Only one middleware file is supported per project.

Exports

middleware function

NextRequest
The incoming NextRequest object, which extends the Web Request API with:
  • request.nextUrl — a parsed URL object with a searchParams helper and pathname
  • request.cookies — read/write access to request cookies
  • request.headers — read access to request headers
The function should return a NextResponse or Response, or undefined to pass through.

config (optional)

Export a config object to control which paths the middleware runs on:
middleware.ts
matcher accepts:
  • A single string: '/about/:path*'
  • An array of strings
  • Regular expressions (as strings)
Matcher rules:
  • Must start with /
  • Named parameters like :path match a single segment
  • :path* matches zero or more segments
  • Negative lookaheads (?!...) exclude paths

NextResponse API

Returns a redirect response to a new URL. The original URL is not loaded.
Rewrites the request to a different URL without changing the URL visible to the user.
Continues the middleware chain, optionally modifying headers.

Examples

Redirecting unauthenticated users

middleware.ts

Rewriting requests

middleware.ts

Setting request headers

middleware.ts

Setting response cookies

middleware.ts

Matching multiple paths

middleware.ts
Middleware runs on the Edge Runtime by default. Node.js APIs are not available. Use the experimental-edge runtime config if you need them.