fix: prevent 404 for routes consisting solely of an optional parameter (#2798)

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Gabriel Halle
2026-03-29 21:27:18 +02:00
committed by GitHub
co-authored by Bartek Iwańczuk Claude Opus 4.6
parent be813e0dfd
commit 669f62a32a
3 changed files with 23 additions and 1 deletions
+1
View File
@@ -78,6 +78,7 @@ they might match:
| `blog/[slug]/comments.ts` | `/blog/:slug/comments` | `/blog/foo/comments` |
| `old/[...path].ts` | `/old/:path*` | `/old/foo`, `/old/bar/baz` |
| `docs/[[version]]/index.ts` | `/docs{/:version}?` | `/docs`, `/docs/latest`, `/docs/canary` |
| `[[name]].ts` | `/{:name}?` | `/`, `/foo`, `/bar` |
Advanced use-cases can require that a more complex pattern be used for matching.
A custom [URL pattern][urlpattern] can be specified in the route configuration.
+17 -1
View File
@@ -196,6 +196,7 @@ export function pathToPattern(
let route = "";
let nonOptionalSegments = 0;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
@@ -268,7 +269,12 @@ export function pathToPattern(
}
}
route += (optional ? "" : "/") + pattern;
if (optional) {
route += pattern;
} else {
nonOptionalSegments++;
route += "/" + pattern;
}
}
// Case: /(group)/index.tsx
@@ -276,6 +282,16 @@ export function pathToPattern(
route = "/";
}
// Handles all cases where a route starts with
// an optional parameter and does not contain
// any non-group and non-optional segments after
// Case: /[[id]].tsx
// Case: /(group)/[[id]].tsx
// Case: /(group)/[[name]]/(group2)/index.tsx
if (route.startsWith(`{/`) && nonOptionalSegments === 0) {
route = route.replace("{/", "/{");
}
return route;
}
+5
View File
@@ -193,6 +193,11 @@ Deno.test("pathToPattern", async (t) => {
).toEqual(
"/foo{/:name}?/bar{/:bob}?",
);
expect(
pathToPattern("(group)/[[name]]/(group2)/index"),
).toEqual(
"/{:name}?",
);
});
await t.step("throws on invalid patterns", () => {