Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/pink-years-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@opennextjs/aws": patch
---

fix: Correct external URL detection in isExternal using proper URL parsing

Replaces substring-based host matching with URL parsing to correctly determine whether a rewritten URL is external.
This fixes an issue where NextResponse.rewrite() would treat certain external URLs as internal when their pathname contained the host as a substring, causing unexpected 404s during middleware rewrites.
12 changes: 10 additions & 2 deletions packages/open-next/src/core/routing/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,18 @@ import { generateMessageGroupId } from "./queue.js";
export function isExternal(url?: string, host?: string) {
if (!url) return false;
const pattern = /^https?:\/\//;
if (!pattern.test(url)) return false;

if (host) {
return pattern.test(url) && !url.includes(host);
try {
const parsedUrl = new URL(url);
return parsedUrl.host !== host;
} catch {
// If URL parsing fails, fall back to substring check
return !url.includes(host);
}
}
return pattern.test(url);
return true;
}

export function convertFromQueryString(query: string) {
Expand Down
18 changes: 18 additions & 0 deletions packages/tests-unit/tests/core/routing/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,24 @@ describe("isExternal", () => {
it("returns false for absolute https url same host", () => {
expect(isExternal("https://absolute.com/path", "absolute.com")).toBe(false);
});

it("returns true for absolute https url different host but same host in path", () => {
expect(isExternal("https://absolute.com/local.com", "local.com")).toBe(
true,
);
});

it("returns false for same host with port", () => {
expect(isExternal("https://localhost:3000/path", "localhost:3000")).toBe(
false,
);
});

it("returns true for different port on same hostname", () => {
expect(isExternal("https://localhost:3001/path", "localhost:3000")).toBe(
true,
);
});
});

describe("convertFromQueryString", () => {
Expand Down
Loading