0
0
NextjsHow-ToBeginner · 3 min read

How to Match Routes in Middleware in Next.js

In Next.js, you match routes in middleware by using the matcher property in the middleware.ts file. This property accepts an array of route patterns where the middleware should run, allowing you to target specific paths or groups of paths.
📐

Syntax

The matcher property in Next.js middleware config defines which routes the middleware applies to. It accepts an array of strings with route patterns. Patterns can include wildcards like * to match multiple paths.

Example parts:

  • matcher: ['/about', '/dashboard/*'] - runs middleware on /about and all routes under /dashboard/.
  • export const config = { matcher: [...] } - exports the config object with matcher.
typescript
export const config = {
  matcher: ['/about', '/dashboard/:path*']
};
💻

Example

This example shows middleware that runs only on /profile and any route under /settings. It logs a message and continues the request.

typescript
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  console.log('Middleware running on:', request.nextUrl.pathname);
  return NextResponse.next();
}

export const config = {
  matcher: ['/profile', '/settings/:path*']
};
Output
Middleware running on: /profile Middleware running on: /settings/account Middleware does not run on /about or /home
⚠️

Common Pitfalls

Common mistakes when matching routes in Next.js middleware include:

  • Not exporting the config object with matcher, so middleware runs on all routes.
  • Using incorrect pattern syntax, like missing :path* for nested routes.
  • Expecting middleware to run on routes not included in matcher.

Correct pattern example: '/dashboard/:path*' matches /dashboard and all subpaths.

Wrong pattern example: '/dashboard/*' is invalid in Next.js matcher.

typescript
/* Wrong way - no matcher, middleware runs everywhere */
export function middleware(request) {
  return NextResponse.next();
}

/* Right way - specify matcher for targeted routes */
export const config = {
  matcher: ['/dashboard/:path*']
};
📊

Quick Reference

FeatureDescriptionExample
matcherArray of route patterns where middleware runs['/about', '/blog/:path*']
:path*Wildcard to match nested routes'/dashboard/:path*' matches /dashboard and subpaths
No matcherMiddleware runs on all routesNo config export or empty matcher
Invalid wildcardUsing '*' alone is invalidUse ':path*' instead of '*'

Key Takeaways

Use the exported config object with matcher to specify middleware routes.
Use ':path*' to match nested routes under a path.
Middleware runs only on routes matched by the matcher patterns.
Avoid using '*' wildcard alone; use ':path*' for Next.js route matching.
Without matcher, middleware runs on all routes by default.