Proposal: Expose a createRouteMatcher utility in next/middleware to simplify route matching #82196
Replies: 1 comment
-
Hi @mattiamalonni, Thanks for sharing this proposal! I think exposing a createRouteMatcher utility inside next/middleware would be a great addition. Currently, middleware authors often need to replicate route matching logic that feels duplicated and error-prone. Your example demonstrates perfectly how much simpler and more maintainable the middleware code would be with a dedicated matcher helper. A few points that might help strengthen the proposal: Having a first-party, official utility encourages consistency across apps and reduces bugs caused by brittle string comparisons or regex mistakes. Supporting simple glob or regex pattern matching (like your /dashboard(.*)) is powerful yet familiar. It can improve readability and maintainability for apps with mixed public/private route logic or conditional redirects. Aligning this with Next.js’ existing matcher config syntax would make it intuitive. I also appreciate that you’ve built a working open-source package (next-path-matcher) already. Contributing this upstream or collaborating with the Next.js team could benefit the entire community. Looking forward to seeing this progress. Please let me know if I can help test or provide feedback! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Goals
middleware.config.matcher
and runtime path-checking code.Non-Goals
matcher
configuration inmiddleware.config.ts
.Background
Next.js provides the
matcher
option inmiddleware.config.ts
to determine which routes should execute the middleware. However, developers frequently need to replicate this logic inside the middleware itself to support conditional flows.For example: checking if the current request matches a protected route pattern like
/profile
or '/dashboard/*', or skipping auth logic for public routes like/login
,/about
, etc.Currently, developers must either hardcode brittle string comparisons or reimplement their own route matching logic.
For example:
Proposal
Similar to clerk
This would be especially useful for applications with mixed public/private routes or complex redirect rules in middleware.
✅ I have already created a working implementation as an open-source package next-path-matcher and would be happy to contribute or align it with the official Next.js API if there’s interest.
Beta Was this translation helpful? Give feedback.
All reactions