Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/khaki-coins-travel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"next-ws": patch
---

Fix incorrect priority on route matching
31 changes: 26 additions & 5 deletions src/server/helpers/match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,33 @@ export function findMatchingRoute(
...nextServer.getAppPathRoutes(),
};

let matchedRoute = undefined;
for (const [routePath, [filePath]] of Object.entries(appPathRoutes)) {
if (!routePath || !filePath) continue;
const sortedRoutes = Object.entries(appPathRoutes)
.filter(([routePath, file]) => routePath && file)
.sort(([a], [b]) => scoreRoute(b) - scoreRoute(a));

for (const [routePath, [filePath]] of sortedRoutes) {
const realPath = `${basePath}${routePath}`;
const routeParams = getRouteParams(realPath, requestPathname);
if (routeParams) matchedRoute = { filename: filePath, params: routeParams };
if (routeParams) {
return { filename: filePath, params: routeParams };
}
}
return matchedRoute;
}

function scoreRoute(routePath: string) {
const parts = routePath.split('/').filter(Boolean);

let score = 0;
// Root path
if(parts.length === 0) score = Infinity;
for (const part of parts) {
// Optional catch-all
if (part.startsWith('[[...')) score += -1;
// Catch-all
else if (part.startsWith('[...')) score += 2;
else if (part.startsWith('[')) score += 2;
else score += 3;
}

return score + parts.length;
}