Incorrect path matching when using nested paths
See original GitHub issueI’m running into some unexpected problems when defining nested paths. I was hoping you could set me on the right path (no pun intended 😄). I have created a small example to demonstrate.
Problem
var Router5 = require('router5').default;
var router = new Router5();
router
.addNode('personList', '/persons/')
.addNode('personDetail', '/persons/:personId');
var match = router.matchPath('/persons/jwoudenberg');
console.log(match); //=> null
In the example above, the path /persons/jwoudenberg does not result in a match. I would expect it to match the personDetail route.
Analsysis
After looking through the code I see what happens. The path is a partial match with the personList route. Router5 looks to complete the match by going through the child router of personList, but none exist, so it gives up. Removing the personList route makes /persons/jwoudenberg resolve correctly.
Solutions
I can imagine I could get it to work by defining personDetail as a child of personList. I was kind of hoping though that I could get around using this extra functionality, which I otherwise don’t need. Certainly for new users, I think this can be confusing (as it was for me 😄).
Some possible solutions I see:
- Sort routes by the amount of segments they contain in descending order before matching. That way the most specific routes should be matched first.
- Don’t bail on the first failing partial match. If there’s child routes left that haven’t been tried yet, continue with those.
I’m looking forward to hearing your thoughts!
Issue Analytics
- State:
- Created 8 years ago
- Comments:9 (7 by maintainers)

Top Related StackOverflow Question
OK, I’ll look into this this week.
Fixed in version 3.0.2.
There is one edge case left which requires a bit more work (along the lines of what @jwoudenberg mentioned with Don’t bail on the first failing partial match. If there’s child routes left that haven’t been tried yet, continue with those.). Considering @jwoudenberg example:
Everything works as long as
postIddoesn’t start with'new'. Otherwise @jwoudenberg other case (with persons) and @tokenvolt example should be working fine.For those interested: https://github.com/troch/route-node/blob/master/modules/RouteNode.js#L58-L83 for the improved sorting logic.
If any issues let me know. Thanks for your patience.