From 8ece96204b846967ba291ea1d67ce3d540ba5dae Mon Sep 17 00:00:00 2001 From: Dario Piotrowicz Date: Mon, 4 Dec 2023 17:05:13 +0000 Subject: [PATCH] Properly handle external middleware rewrites (#568) --- .changeset/olive-needles-lay.md | 22 +++++++++++++++++++ .../templates/_worker.js/routes-matcher.ts | 7 +++++- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 .changeset/olive-needles-lay.md diff --git a/.changeset/olive-needles-lay.md b/.changeset/olive-needles-lay.md new file mode 100644 index 000000000..b48882ded --- /dev/null +++ b/.changeset/olive-needles-lay.md @@ -0,0 +1,22 @@ +--- +'@cloudflare/next-on-pages': patch +--- + +fix external middleware rewrites + +Currently Middleware rewrites (`NextResponse.rewrite()`) assume that the rewrite destination +is on the same host as the application, meaning that the following operations would work as intended: + +```ts +NextResponse.rewrite(new URL('/rewrite-dest', request.url)); +``` + +while something like this would not: + +```ts +return NextResponse.rewrite( + new URL('https://my-customer-rewrite-site.come/rewrite-dest', request.url), +); +``` + +Remove such assumption and allow such external rewrites to take place (as they do on Vercel) diff --git a/packages/next-on-pages/templates/_worker.js/routes-matcher.ts b/packages/next-on-pages/templates/_worker.js/routes-matcher.ts index b9a523390..d4965360a 100644 --- a/packages/next-on-pages/templates/_worker.js/routes-matcher.ts +++ b/packages/next-on-pages/templates/_worker.js/routes-matcher.ts @@ -189,9 +189,14 @@ export class RoutesMatcher { const rewriteKey = 'x-middleware-rewrite'; const rewriteHeader = resp.headers.get(rewriteKey); + if (rewriteHeader) { const newUrl = new URL(rewriteHeader, this.url); - this.path = newUrl.pathname; + + const rewriteIsExternal = this.url.hostname !== newUrl.hostname; + + this.path = rewriteIsExternal ? `${newUrl}` : newUrl.pathname; + applySearchParams(this.searchParams, newUrl.searchParams); resp.headers.delete(rewriteKey);