From b8c114ee08766ec56d9155c5c02be275973838c6 Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 11 Sep 2024 22:53:17 +0100 Subject: [PATCH] Fix issue where an incoming query string got lost in a hash redirect --- .../__tests__/asset-server/handler.test.ts | 15 +++++++++++++++ packages/pages-shared/asset-server/handler.ts | 4 +++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/pages-shared/__tests__/asset-server/handler.test.ts b/packages/pages-shared/__tests__/asset-server/handler.test.ts index 78551e76e933..1bf81649f306 100644 --- a/packages/pages-shared/__tests__/asset-server/handler.test.ts +++ b/packages/pages-shared/__tests__/asset-server/handler.test.ts @@ -998,6 +998,21 @@ describe("asset-server handler", () => { "https://foobar.com/#def?test=abc" ); }); + + // Query string needs to be _before_ the hash + test("redirects to a hash with an incoming query cross-origin", async () => { + const { response } = await getTestResponse({ + request: "https://foo.com/bar?test=abc", + metadata: createMetadataObjectWithRedirects([ + { from: "/bar", to: "https://foobar.com/#heading", status: 301 }, + ]), + }); + + expect(response.status).toBe(301); + expect(response.headers.get("Location")).toBe( + "https://foobar.com/?test=abc#heading" + ); + }); }); }); diff --git a/packages/pages-shared/asset-server/handler.ts b/packages/pages-shared/asset-server/handler.ts index 87f106a2149e..7dc754853e1f 100644 --- a/packages/pages-shared/asset-server/handler.ts +++ b/packages/pages-shared/asset-server/handler.ts @@ -227,7 +227,9 @@ export async function generateHandler< ? `${destination.pathname}${destination.search || search}${ destination.hash }` - : `${destination.href}${destination.search ? "" : search}`; + : `${destination.href.slice(0, -(destination.search.length + destination.hash.length))}${ + destination.search ? "" : search + }${destination.hash}`; switch (status) { case 301: