How do you limit which routes your middleware actually applies to?
Short answer
You export a config object with a matcher array from your middleware file, specifying the exact paths or patterns where the middleware should run, preventing it from executing unnecessarily on routes where it is not needed, such as static assets.
Advertisement
AModel answer
You export a config object with a matcher array from your middleware file, specifying the exact paths or patterns where the middleware should run, preventing it from executing unnecessarily on routes where it is not needed, such as static assets.
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*']
};Real-world example
A team configures their authentication middleware to only run on dashboard and admin routes, avoiding unnecessary overhead on public marketing pages that do not need any authentication checks.
Likely follow-ups
- Can you use a regular expression in the matcher configuration?
- What happens to routes not included in the matcher?
Related topics