Middleware
Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
Middleware runs before cached content and routes are matched. See Matching Paths for more details.
Convention
Use the file middleware.ts (or .js) in the root of your project to define Middleware. For example, at the same level as pages or app, or inside src if applicable.
Example
Matching Paths
Middleware will be invoked for every route in your project. The following is the execution order:
headersfromnext.config.jsredirectsfromnext.config.js- Middleware (
rewrites,redirects, etc.) beforeFiles(rewrites) fromnext.config.js- Filesystem routes (
public/,_next/static/,pages/,app/, etc.) afterFiles(rewrites) fromnext.config.js- Dynamic Routes (
/blog/[slug]) fallback(rewrites) fromnext.config.js
There are two ways to define which paths Middleware will run on:
Matcher
matcher allows you to filter Middleware to run on specific paths.
You can match a single path or multiple paths with an array syntax:
The matcher config allows full regex so matching like negative lookaheads or character matching is supported. An example of a negative lookahead to match all except specific paths can be seen here:
You can also ignore prefetches (from next/link) that don't need to go through the Middleware using the missing array:
Good to know
The matcher values need to be constants so they can be statically analyzed at build-time. Dynamic values such as variables will be ignored.
Configured matchers:
- MUST start with
/ - Can include named parameters:
/about/:pathmatches/about/aand/about/bbut not/about/a/c - Can have modifiers on named parameters (starting with
:):/about/:path*matches/about/a/b/cbecause*is zero or more.?is zero or one and+one or more - Can use regular expression enclosed in parenthesis:
/about/(.*)is the same as/about/:path*
Read more details on path-to-regexp documentation.
Good to know
For backward compatibility, Next.js always considers /public as /public/index. Therefore, a matcher of /public/:path will match.
Conditional Statements
NextResponse
The NextResponse API allows you to:
redirectthe incoming request to a different URLrewritethe response by displaying a given URL- Set request headers for API Routes,
getServerSideProps, andrewritedestinations - Set response cookies
- Set response headers
To produce a response from Middleware, you can:
rewriteto a route (Page or Edge API Route) that produces a response- return a
NextResponsedirectly. See Producing a Response
Using Cookies
Cookies are regular headers. On a Request, they are stored in the Cookie header. On a Response they are in the Set-Cookie header. Next.js provides a convenient way to access and manipulate these cookies through the cookies extension on NextRequest and NextResponse.
- For incoming requests,
cookiescomes with the following methods:get,getAll,set, anddeletecookies. You can check for the existence of a cookie withhasor remove all cookies withclear. - For outgoing responses,
cookieshave the following methodsget,getAll,set, anddelete.
Setting Headers
You can set request and response headers using the NextResponse API (setting request headers is available since Next.js v13.0.0).
Good to know
Avoid setting large headers as it might cause 431 Request Header Fields Too Large error depending on your backend web server configuration.
Producing a Response
You can respond from Middleware directly by returning a Response or NextResponse instance. (This is available since Next.js v13.1.0)
waitUntil and NextFetchEvent
The NextFetchEvent object extends the native FetchEvent object, and includes the waitUntil() method.
The waitUntil() method takes a promise as an argument, and extends the lifetime of the Middleware until the promise settles. This is useful for performing work in the background.
Advanced Middleware Flags
In v13.1 of Next.js two additional flags were introduced for middleware, skipMiddlewareUrlNormalize and skipTrailingSlashRedirect to handle advanced use cases.
skipTrailingSlashRedirect disables Next.js redirects for adding or removing trailing slashes. This allows custom handling inside middleware to maintain the trailing slash for some paths but not others, which can make incremental migrations easier.
skipMiddlewareUrlNormalize allows disabling the URL normalizing Next.js does to make handling direct visits and client-transitions the same. There are some advanced cases where you need full control using the original URL which this unlocks.
Runtime
Middleware currently only supports the Edge runtime. The Node.js runtime can not be used.
Version History
| Version | Changes |
|---|---|
v13.1.0 | Advanced Middleware flags added |
v13.0.0 | Middleware can modify request headers, response headers, and send responses |
v12.2.0 | Middleware is stable, please see the upgrade guide |
v12.0.9 | Enforce absolute URLs in Edge Runtime (PR) |
v12.0.0 | Middleware (Beta) added |
Last updated