Skip to content
On this page

Middleware (Beta)

Version History
v12.0.9Enforce absolute URLs in Edge Runtime (PR)
v12.0.0Middleware (Beta) added.

Middleware enables you to use code over configuration. This gives you full flexibility in Next.js, because you can 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.


  1. Install the latest version of Next.js:
npm install next@latest
  1. Then, create a middleware.ts file under your project root directory.

  2. 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.redirect(new URL(`/login?from=${req.nextUrl.pathname}`, req.url))

In this example, we use the standard Web API Response (MDN).


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


Middleware can be used for anything that shares logic for a set of pages, including:

Execution Order

Middleware runs directly after redirects and headers, before the first filesystem lookup. This excludes /_next files.


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.

Middleware API ReferenceLearn more about the supported APIs for Middleware.

Edge RuntimeLearn more about the supported Web APIs available.