middleware.ts
Convention
Create amiddleware.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
The incoming NextRequest object, which extends the Web
Request API with:request.nextUrl— a parsed URL object with asearchParamshelper andpathnamerequest.cookies— read/write access to request cookiesrequest.headers— read access to request headers
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)
- Must start with
/ - Named parameters like
:pathmatch a single segment :path*matches zero or more segments- Negative lookaheads
(?!...)exclude paths
NextResponse API
NextResponse.redirect
NextResponse.redirect
Returns a redirect response to a new URL. The original URL is not loaded.
NextResponse.rewrite
NextResponse.rewrite
Rewrites the request to a different URL without changing the URL visible to the user.
NextResponse.next
NextResponse.next
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.