Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Next.js 16+ · Directive

middleware

Middleware runs before a request completes and can redirect, rewrite, or modify headers. In Next.js 16, the middleware convention is deprecated and replaced by Proxy, except when retaining Edge-runtime usage.

How it works

Middleware runs before a request is completed and can alter routing or headers based on the incoming request. In Next.js 16, the convention is deprecated in favor of Proxy; retain Middleware when the Edge runtime is required.

Syntax

export function middleware(request: Request): Response | NextResponse

Parameters

NameTypeDescription
requestRequestThe incoming request passed to the Middleware function.

Returns

A Response or NextResponse instance, or no response when continuing the request.

Key points

  • Middleware executes before the request finishes, enabling request-time routing decisions.
  • Use the incoming request to redirect, rewrite, or modify request and response headers.
  • Define Middleware in a root-level middleware.ts or middleware.js file.
  • Export matcher configuration to limit execution to selected URL paths.
  • The legacy Middleware convention is limited to the Edge runtime on the documented page.

Example: middleware.ts

export function middleware(request: Request) {
  return Response.redirect(new URL('/login', request.url))
}

export const config = {
  matcher: ['/dashboard/:path*'],
}

Redirects dashboard requests to the login page before the request completes.

When to use it

Authentication redirects

Protect dashboard or account routes by redirecting unauthenticated requests to login.

URL rewriting

Send a request to a different route while keeping the visible URL unchanged.

Request and response header changes

Add or alter headers before a route handler or page processes the request.

  • Proxy
  • NextResponse
  • matcher
  • Edge runtime
  • redirect
  • rewrite

Source: Middleware. Checked 2026-10-15.