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);