Skip to content

Commit 0de7511

Browse files
authored
Preserve the original x-forwarded-host header if it is set. (#10887)
* Preserve the original x-forwarded-host header if it is set * Add changeset * PR feedback
1 parent 1334102 commit 0de7511

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

.changeset/five-files-throw.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@cloudflare/vite-plugin": patch
3+
---
4+
5+
Preserve the original `x-forwarded-host` header if it is set.

packages/vite-plugin-cloudflare/playground/worker-♫/__tests__/worker.spec.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,15 @@ test("basic dev logging", async () => {
3232
expect(serverLogs.errors.join()).toContain("__console warn__");
3333
});
3434

35-
test("receives the original host as the `X-Forwarded-Host` header", async () => {
35+
test("receives the original `x-forwarded-host` header if it is set", async () => {
36+
const response = await fetch(`${viteTestUrl}/x-forwarded-host`, {
37+
headers: { "x-forwarded-host": "example.com:8080" },
38+
});
39+
40+
expect(await response.text()).toBe("example.com:8080");
41+
});
42+
43+
test("receives the Vite server host as the `x-forwarded-host` header if the `x-forwarded-host` header is not set", async () => {
3644
const testUrl = new URL(viteTestUrl);
3745
await vi.waitFor(
3846
async () =>

packages/vite-plugin-cloudflare/src/utils.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,16 @@ export function createRequestHandler(
7070
}
7171

7272
function toMiniflareRequest(request: Request): MiniflareRequest {
73-
// We set the X-Forwarded-Host header to the original host as the `Host` header inside a Worker will contain the workerd host
7473
const host = request.headers.get("Host");
75-
if (host) {
74+
const xForwardedHost = request.headers.get("X-Forwarded-Host");
75+
76+
if (host && !xForwardedHost) {
77+
// Set the `x-forwarded-host` header to the host of the Vite server if it is not already set
78+
// Note that the `host` header inside the Worker will contain the workerd host
79+
// TODO: reconsider this when adopting `miniflare.dispatchFetch` as it may be possible to provide the Vite server host in the `host` header
7680
request.headers.set("X-Forwarded-Host", host);
7781
}
82+
7883
// Undici sets the `Sec-Fetch-Mode` header to `cors` so we capture it in a custom header to be converted back later.
7984
const secFetchMode = request.headers.get("Sec-Fetch-Mode");
8085
if (secFetchMode) {

0 commit comments

Comments
 (0)