4.3 KiB
description |
---|
Learn how to use Middleware in Next.js to run code before a request is completed. |
Middleware (Beta)
Version History
Version | Changes |
---|---|
canary |
Preparing for stability, see upgrade guide |
v12.0.9 |
Enforce absolute URLs in Edge Runtime (PR) |
v12.0.0 |
Middleware (Beta) added. |
Middleware enables you to run code before a request is completed. Based on the user's incoming request, you can modify the response by rewriting, redirecting, adding headers, or even streaming HTML.
Usage
- Install the canary version of Next.js:
npm install next@canary
-
Then, create a
middleware.ts
file under your project root directory. -
Finally, export a middleware function from the
middleware.ts
file.
// middleware.ts
import type { NextRequest, NextResponse } from 'next/server'
import { areCredentialsValid } from '../lib'
export function middleware(req: NextRequest) {
if (areCredentialsValid(req.headers.get('authorization'))) {
return NextResponse.next()
}
return NextResponse.redirect(
new URL(`/login?from=${req.nextUrl.pathname}`, req.url)
)
}
In this example, we use the standard Web API Response (MDN).
API
Middleware is created by using a middleware
function that lives inside a middleware
file. Its API is based upon the native FetchEvent
, Response
, and Request
objects.
These native Web API objects are extended to give you more control over how you manipulate and configure a response, based on the incoming requests.
The function signature:
import type { NextFetchEvent } from 'next/server'
import type { NextRequest } from 'next/server'
export type Middleware = (
request: NextRequest,
event: NextFetchEvent
) => Promise<Response | undefined> | Response | undefined
The function can be a default export and as such, does not have to be named middleware
. Though this is a convention. Also note that you only need to make the function async
if you are running asynchronous code.
Read the full Middleware API reference, note Node.js APIs are not supported in this environment
Examples
Middleware can be used for anything that shares logic for a set of pages, including:
- Authentication
- Bot protection
- Redirects and rewrites
- Handling unsupported browsers
- Feature flags and A/B tests
- Advanced i18n routing requirements
Execution Order
Middleware runs directly after redirects
and headers
, before the first filesystem lookup. This excludes /_next
files.
Deployment
Middleware uses a strict runtime that supports standard Web APIs like fetch
. This works out of the box using next start
, as well as on Edge platforms like Vercel, which use Edge Functions.