In Next.js, the matcher
configuration allows you to specify which routes your middleware should run on. This is useful when you want to apply middleware selectively to certain pages, API routes, or dynamic paths, rather than applying it globally.
Here’s how to use the matcher
in Next.js middleware.
Basic Usage of matcher
You define the matcher
in the middleware.ts
or middleware.js
file to specify the exact routes or patterns where the middleware should be active. The matcher
is an array of route patterns, and it works with both static and dynamic routes.
Example 1: Apply Middleware to Specific Pages
Let’s say you only want your middleware to run on the /dashboard
and /profile
pages:
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
// Your middleware logic
return NextResponse.next();
}
// Apply middleware only to /dashboard and /profile
export const config = {
matcher: ['/dashboard', '/profile'],
};
In this example, the middleware will only run when the user visits the /dashboard
or /profile
routes.
Example 2: Applying Middleware to Dynamic Routes
You can also use the matcher
to target dynamic routes, such as /user/[id]
. The matcher
allows for dynamic segments and wildcards (*
), making it easy to apply middleware to a range of paths.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
const { pathname } = req.nextUrl;
console.log('Middleware active on:', pathname);
return NextResponse.next();
}
// Apply middleware to all /user/[id] dynamic routes
export const config = {
matcher: ['/user/:path*'],
};
In this case, :path*
acts as a wildcard, so the middleware will match any route starting with /user/
, such as /user/123
, /user/abc
, etc.
Example 3: Exclude Certain Pages with matcher
You can also use the matcher
to exclude certain paths from your middleware by simply not listing them in the configuration. For example, if you want to apply middleware to all routes except for /login
and /signup
:
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
const { pathname } = req.nextUrl;
if (pathname.startsWith('/login') || pathname.startsWith('/signup')) {
return NextResponse.next(); // Skip middleware for login and signup
}
// Your custom middleware logic for other routes
return NextResponse.next();
}
// Apply middleware to all routes except login and signup
export const config = {
matcher: ['/:path*'],
};
Example 4: Using Regular Expressions in matcher
The matcher
also supports regular expressions for fine-grained control over which routes the middleware applies to. For example, if you want to run middleware only for API routes that start with /api/admin
:
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
// Custom middleware logic
return NextResponse.next();
}
// Apply middleware to only /api/admin/* routes
export const config = {
matcher: ['/api/admin/:path*'],
};
Summary
- Static Routes: Specify paths like
/dashboard
,/profile
, etc. - Dynamic Routes: Use
:path*
to match dynamic segments. - Wildcard: Use
:path*
to match all subpaths. - Excluding Routes: Apply conditions in your middleware logic or use the
matcher
to exclude specific routes. - API Routes: Apply middleware to API routes by matching
/api/*
or more specific paths.
By using the matcher
in Next.js middleware, you can ensure that your middleware only runs on the routes where it’s needed, improving performance and flexibility.
Lior Amsalem embarked on his software engineering journey in the early 2000s, Diving into Pascal with a keen interest in creating, developing, and working on new technologies. Transitioning from his early teenage years as a freelancer, Lior dedicated countless hours to expanding his knowledge within the software engineering domain. He immersed himself in learning new development languages and technologies such as JavaScript, React, backend, frontend, devops, nextjs, nodejs, mongodb, mysql and all together end to end development, while also gaining insights into business development and idea implementation.
Through his blog, Lior aims to share his interests and entrepreneurial journey, driven by a desire for independence and freedom from traditional 9-5 work constraints.
Leave a Reply