Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Middleware: Matchers, Redirects, Rewrites, and Why It Is Not an Auth Guard

One function before routing, on the edge runtime. Matcher grammar, redirect versus rewrite, and the bypass that makes in-page authorization mandatory.

~4 min readNext.js
#Next.js#Middleware#Routing#Security
3D illustration of request arrows passing a filter gate that branches into pass, rewrite and redirect paths

Quick Summary

Middleware is one function that runs before a request is matched to a route. It receives a NextRequest, and can pass the request through (NextResponse.next()), redirect it, rewrite it to another path, or return a response of its own. In Next.js 16 the file was renamed proxy.ts (with middleware.ts still supported under a deprecation warning); the semantics are the same.

It is the right place for things that must happen for every request cheaply: locale detection, canonical-host redirects, auth-cookie gating, A/B assignment, and header injection. It is the wrong place for anything that needs a database, heavy computation, or a Node-only library — middleware runs in the Edge runtime, where pg, fs, and most ORMs do not work.

export const config = { matcher: [...] } narrows which requests invoke it. Without a matcher, middleware runs on every request including static assets, and every image and chunk pays the function's latency. The matcher is a path pattern array with a specific grammar: each entry must start with /, and regular expressions are supported but must not use capturing groups wrongly.

Basic Syntax & Core Signatures

ts
// middleware.ts (Next.js 16: proxy.ts) at the project root or under src/ import { NextRequest, NextResponse } from "next/server"; export function middleware(request: NextRequest) { const { pathname, search } = request.nextUrl; const session = request.cookies.get("session")?.value; // 1. Gate an area if (pathname.startsWith("/dashboard") && !session) { const url = request.nextUrl.clone(); url.pathname = "/login"; url.searchParams.set("next", pathname + search); return NextResponse.redirect(url); } // 2. Canonical host const host = request.headers.get("host"); if (host === "example.com") { return NextResponse.redirect(`https://www.example.com${pathname}${search}`, 308); } // 3. Forward a header to the app const headers = new Headers(request.headers); headers.set("x-pathname", pathname); return NextResponse.next({ request: { headers } }); } export const config = { matcher: ["/dashboard/:path*", "/api/:path*", "/((?!_next/static|_next/image|favicon.ico).*)"], };
ts
// Rewrite: same URL, different content (A/B test, legacy path) const bucket = request.cookies.get("ab")?.value ?? (Math.random() < 0.5 ? "a" : "b"); const res = NextResponse.rewrite(new URL(`/${bucket}${request.nextUrl.pathname}`, request.url)); res.cookies.set("ab", bucket, { path: "/", maxAge: 60 * 60 * 24 * 30 }); return res;
ts
// Returning a response without a route if (request.nextUrl.pathname === "/api/ping") { return new Response("pong", { status: 200, headers: { "x-edge": "1" } }); }

Key Comparison Table

MethodURL seen by the browserRenderingUse for
NextResponse.next()UnchangedContinues to the routeHeaders, gating
NextResponse.redirect(url, 307/308)ChangesNew requestAuth, canonical host
NextResponse.rewrite(url)UnchangedDifferent route or contenti18n, A/B, legacy paths
NextResponse.json(body)UnchangedNo route runsCheap API, maintenance mode
CapabilityAvailable in middleware
cookies, headers, URL, fetchYes
fs, path, Node crypto moduleNo (Edge runtime)
Prisma, pg, most driversNo
JWT verification (jose)Yes
Reading the request bodyOnly by cloning the request
Long-running workNo
SymptomMeaning
Middleware runs on every image requestNo matcher
Module not found: Can't resolve 'fs'Node API in edge code
Redirect loopMatcher also matches the redirect target
Auth bypass reportedMiddleware is not a security boundary

Practical Edge Cases & Deep Dives

1. The matcher, precisely

ts
export const config = { matcher: [ "/about/:path*", // named path segment "/api/:path*", "/blog/:slug", // one segment, no children "/((?!_next|api|favicon.ico).*)", // everything except internals ], };

Patterns are path-to-regexp style with one important restriction: a regex entry must not contain a capturing group that is not a named param, and it must start with /. Excluding _next/static, _next/image, and font or image assets is not optional for performance — middleware adds a function invocation to every matched request, and it can be the slowest thing on a page of thirty assets.

Two matcher mistakes recur: excluding /login from an auth matcher and then leaving the redirect target unprotected (a loop), and matching /api broadly while a webhook must bypass it.

2. Middleware is not the security boundary

ts
// Looks like auth. Is not. if (!session) return NextResponse.redirect(new URL("/login", request.url));

A middleware check is a routing decision made before rendering. It can be bypassed by a request that does not run middleware (a direct Server Action invocation, an internal rewrite, a caching layer) and — notably — it was possible before CVE-2025-29927 (fixed in 15.2.3) to skip middleware entirely with a crafted x-middleware-subrequest header. The durable pattern is defence in depth: middleware for UX (no flash of protected content, cheap redirects), and an authorization check inside every page, Server Action, and route handler that touches protected data.

ts
// The check that actually protects data const session = await auth(); if (!session) notFound();

3. Reading and forwarding cookies and headers

ts
const token = request.cookies.get("session")?.value; const res = NextResponse.next(); res.cookies.set({ name: "seen", value: "1", path: "/", httpOnly: true, sameSite: "lax" });

Cookies read in middleware are available to the route through the request. Cookies set on the response are available to the browser and to the next request, but not to the current render — a route cannot read a cookie middleware sets in the same request. Headers are the opposite: NextResponse.next({ request: { headers: newHeaders } }) overwrites the request headers the app sees, which is how x-pathname or a resolved locale is passed down. In server components, read them with await headers().

4. Edge runtime constraints that break a build

text
Error: The edge runtime does not support Node.js 'crypto' module. Did you mean to use 'crypto' (Web Crypto API) instead?

Middleware runs on a runtime with Web standards only: crypto.subtle, TextEncoder, fetch, URL, AbortController. JSON Web Tokens verify with jose (edge-compatible) rather than jsonwebtoken (Node crypto). Session stores at the edge must be HTTP calls — Upstash Redis, a KV binding — not a Postgres driver. If the logic genuinely needs Node, it does not belong in middleware; run it in a route handler or a Server Action instead.

5. Locale and host routing without breaking the app

ts
const locale = request.cookies.get("locale")?.value ?? detectLocale(request.headers.get("accept-language")); if (!pathname.startsWith(`/${locale}`)) { return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url)); }

Two rules keep this stable. The redirect target must not match the same condition again (check pathname.startsWith, not a bare rewrite), and static assets and API routes must be excluded from the matcher or every asset 307s to a locale path. Host-based routing to a subdomain follows the same shape, with request.headers.get("host") and a 308 so a POST body survives the redirect.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Can't resolve 'fs' / 'crypto'Node module in edge codeWeb APIs, or move the logic out
Redirect loopMatcher covers the redirect targetExclude the target path
Every image request slowedNo matcher exclusion for _nextNarrow the matcher
Set-Cookie missingSet on the NextRequestSet on the NextResponse
Cookie set here unreadable in the pageSame-request timingRead it on the next request
Auth bypassMiddleware treated as enforcementRe-check in the page/action
Header added but not visibleSet on the response instead of the requestNextResponse.next({ request: { headers } })
307 loses a POST bodyTemporary redirect semanticsUse 308 for method preservation
Middleware not runningFile in the wrong placeRoot or src/, named middleware.ts / proxy.ts
Build fails after upgrading to 16middleware.ts deprecationRename to proxy.ts

Middleware is a routing layer with edge-runtime limits and a per-request cost. Use it to decide where a request goes, keep authorization where the data is, and keep the matcher as narrow as the feature allows.

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.