diff --git a/.changeset/fuzzy-ads-rush.md b/.changeset/fuzzy-ads-rush.md new file mode 100644 index 000000000000..d2042bb022e0 --- /dev/null +++ b/.changeset/fuzzy-ads-rush.md @@ -0,0 +1,5 @@ +--- +"wrangler": patch +--- + +Reverse execution order of Pages Functions middlewares diff --git a/packages/wrangler/pages/functions/filepath-routing.test.ts b/packages/wrangler/pages/functions/filepath-routing.test.ts index 6c8eb50cde63..d4dfcbe9a995 100644 --- a/packages/wrangler/pages/functions/filepath-routing.test.ts +++ b/packages/wrangler/pages/functions/filepath-routing.test.ts @@ -1,8 +1,15 @@ import { compareRoutes } from "./filepath-routing"; describe("compareRoutes()", () => { + test("routes / last", () => { + expect(compareRoutes("/", "/foo")).toBeGreaterThanOrEqual(1); + expect(compareRoutes("/", "/:foo")).toBeGreaterThanOrEqual(1); + expect(compareRoutes("/", "/:foo*")).toBeGreaterThanOrEqual(1); + }); + test("routes with fewer segments come after those with more segments", () => { - expect(compareRoutes("/foo", "/foo/bar")).toBe(1); + expect(compareRoutes("/foo", "/foo/bar")).toBeGreaterThanOrEqual(1); + expect(compareRoutes("/foo", "/foo/bar/cat")).toBeGreaterThanOrEqual(1); }); test("routes with wildcard segments come after those without", () => { diff --git a/packages/wrangler/pages/functions/filepath-routing.ts b/packages/wrangler/pages/functions/filepath-routing.ts index c84d3b0db926..1ecc6e5074de 100644 --- a/packages/wrangler/pages/functions/filepath-routing.ts +++ b/packages/wrangler/pages/functions/filepath-routing.ts @@ -162,7 +162,7 @@ export function compareRoutes(a: string, b: string) { method = null; } - const segments = segmentedPath.slice(1).split("/"); + const segments = segmentedPath.slice(1).split("/").filter(Boolean); return [method, segments]; } diff --git a/packages/wrangler/pages/functions/template-worker.ts b/packages/wrangler/pages/functions/template-worker.ts index 3e8f838f6545..fcea78a64cb0 100644 --- a/packages/wrangler/pages/functions/template-worker.ts +++ b/packages/wrangler/pages/functions/template-worker.ts @@ -43,8 +43,8 @@ type WorkerContext = { function* executeRequest(request: Request, env: Env) { const requestPath = new URL(request.url).pathname; - // First, iterate through the routes and execute "middlewares" on partial route matches - for (const route of routes) { + // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches + for (const route of [...routes].reverse()) { if ( route.methods.length && !route.methods.includes(request.method as HTTPMethod)