Back to results for “Authentication”
Next.js › Middleware

How do you limit which routes your middleware actually applies to?

Beginner

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.

Common follow-ups: Can you use a regular expression in the matcher configuration?;What happens to routes not included in the matcher?