Next.jsMedium

What is the matcher config in middleware?

matcher in the exported config limits which request paths run Proxy (middleware). It accepts a path string, an array of paths, path-to-regexp patterns such as /dashboard/:path*, regular expressions, or objects with source, has and missing conditions. Without it, Proxy runs on every request, including static assets.

Pattern syntax

  • /about matches /about and paths under it (anchored at the start).
  • /blog/:slug matches one segment; /blog/:path* zero or more; :path+ one or more; :path? zero or one.
  • Regex in parentheses: /((?!api|_next/static|_next/image|favicon.ico).*) matches everything except those prefixes.
  • All patterns must start with /.

Object form

{ source: "/api/:path*", has: [{ type: "header", key: "authorization" }],
  missing: [{ type: "cookie", key: "session" }], locale: false }

Condition types: header, query, cookie, host.

Rules

  • Values must be constants; Next.js analyzes them at build time. Variables or computed strings are ignored.
  • Excluding _next/static, _next/image and public files is important for performance and to avoid redirecting assets.
  • Prefetch requests can be excluded with missing: [{ type: "header", key: "next-router-prefetch" }].

Matcher vs code checks

Use the matcher for coarse filtering and request.nextUrl.pathname checks inside the function for fine-grained logic. Remember that Server Functions are POSTs to the page route, so excluding a page path also skips Proxy for actions on that page.

Testing

unstable_doesMiddlewareMatch from next/experimental/testing/server asserts whether Proxy runs for a URL.

Code example

tsx
1// proxy.ts
2import { NextResponse, type NextRequest } from "next/server";
3
4export function proxy(request: NextRequest) {
5 return NextResponse.redirect(new URL("/login", request.url));
6}
7
8export const config = {
9 matcher: [
10 // Protect app sections, but only when there is no session cookie
11 {
12 source: "/(dashboard|settings|billing)/:path*",
13 missing: [
14 { type: "cookie", key: "session" },
15 { type: "header", key: "next-router-prefetch" }, // skip prefetches
16 ],
17 },
18 ],
19};
20
21// Common "everything except assets" matcher:
22// matcher: ["/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app