Skip to content

Commit

Permalink
Properly handle external middleware rewrites (#568)
Browse files Browse the repository at this point in the history
  • Loading branch information
dario-piotrowicz authored Dec 4, 2023
1 parent bc216b4 commit 8ece962
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
22 changes: 22 additions & 0 deletions .changeset/olive-needles-lay.md
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 8ece962

Please sign in to comment.