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.

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
// 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).*)"],
};// 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;// 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
| Method | URL seen by the browser | Rendering | Use for |
|---|---|---|---|
NextResponse.next() | Unchanged | Continues to the route | Headers, gating |
NextResponse.redirect(url, 307/308) | Changes | New request | Auth, canonical host |
NextResponse.rewrite(url) | Unchanged | Different route or content | i18n, A/B, legacy paths |
NextResponse.json(body) | Unchanged | No route runs | Cheap API, maintenance mode |
| Capability | Available in middleware |
|---|---|
cookies, headers, URL, fetch | Yes |
fs, path, Node crypto module | No (Edge runtime) |
Prisma, pg, most drivers | No |
JWT verification (jose) | Yes |
| Reading the request body | Only by cloning the request |
| Long-running work | No |
| Symptom | Meaning |
|---|---|
| Middleware runs on every image request | No matcher |
Module not found: Can't resolve 'fs' | Node API in edge code |
| Redirect loop | Matcher also matches the redirect target |
| Auth bypass reported | Middleware is not a security boundary |
Practical Edge Cases & Deep Dives
1. The matcher, precisely
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
// 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.
// The check that actually protects data
const session = await auth();
if (!session) notFound();3. Reading and forwarding cookies and headers
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
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
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
| Symptom | Cause | Fix |
|---|---|---|
Can't resolve 'fs' / 'crypto' | Node module in edge code | Web APIs, or move the logic out |
| Redirect loop | Matcher covers the redirect target | Exclude the target path |
| Every image request slowed | No matcher exclusion for _next | Narrow the matcher |
| Set-Cookie missing | Set on the NextRequest | Set on the NextResponse |
| Cookie set here unreadable in the page | Same-request timing | Read it on the next request |
| Auth bypass | Middleware treated as enforcement | Re-check in the page/action |
| Header added but not visible | Set on the response instead of the request | NextResponse.next({ request: { headers } }) |
| 307 loses a POST body | Temporary redirect semantics | Use 308 for method preservation |
| Middleware not running | File in the wrong place | Root or src/, named middleware.ts / proxy.ts |
| Build fails after upgrading to 16 | middleware.ts deprecation | Rename 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 toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.