From 9e7adc084ba2217ef5c45e5192fc14c4cc4fbb7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sun, 29 Mar 2026 19:11:55 +0000 Subject: [PATCH] fix: middleware not matching routes with optional parameters in fs routing (#3726) Closes #3545 Co-authored-by: Claude Opus 4.6 (1M context) --- packages/fresh/src/router.ts | 16 +++++++++++----- packages/fresh/src/router_test.ts | 8 ++++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/packages/fresh/src/router.ts b/packages/fresh/src/router.ts index d32a1fb6..f0425f54 100644 --- a/packages/fresh/src/router.ts +++ b/packages/fresh/src/router.ts @@ -288,21 +288,27 @@ export function patternToSegments( if (path === "/" || path === "*" || path === "/*") return out; + // Strip optional groups like {/:param}? before segmenting, so that + // /api{/:opt}?/endpoint produces the same segments as /api/endpoint. + // This ensures middleware registered at /api applies to routes with + // optional parameters under /api. + const cleaned = path.replace(/\{[^}]*\}\??/g, ""); + let start = -1; - for (let i = 0; i < path.length; i++) { - const ch = path[i]; + for (let i = 0; i < cleaned.length; i++) { + const ch = cleaned[i]; if (ch === "/") { if (i > 0) { - const raw = path.slice(start + 1, i); + const raw = cleaned.slice(start + 1, i); out.push(raw); } start = i; } } - if (includeLast && start < path.length - 1) { - out.push(path.slice(start + 1)); + if (includeLast && start < cleaned.length - 1) { + out.push(cleaned.slice(start + 1)); } return out; diff --git a/packages/fresh/src/router_test.ts b/packages/fresh/src/router_test.ts index 17767541..947c1e90 100644 --- a/packages/fresh/src/router_test.ts +++ b/packages/fresh/src/router_test.ts @@ -224,6 +224,14 @@ Deno.test("patternToSegments", () => { expect(patternToSegments("/foo/", "")).toEqual(["", "foo"]); expect(patternToSegments("/foo/bar", "", true)).toEqual(["", "foo", "bar"]); + + // Optional params with {/...}? syntax should not split on / inside braces + expect(patternToSegments("/api{/:opt}?/endpoint", "")).toEqual(["", "api"]); + expect(patternToSegments("/api{/:opt}?/endpoint", "", true)).toEqual([ + "", + "api", + "endpoint", + ]); }); Deno.test("mergePath", () => {