Skip to content

Commit 25eaf3b

Browse files
authored
Add X-Forwarded-Host header to requests (#8706)
* Set the x-forwarded-host header on requests * Added changeset
1 parent ecbab5d commit 25eaf3b

File tree

4 files changed

+24
-2
lines changed

4 files changed

+24
-2
lines changed

.changeset/common-baths-fold.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+
Set the `x-forwarded-host` header to the original host in requests. This fixes a bug where libraries such as Clerk would redirect to the workerd host rather than the Vite host.
Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { expect, test } from "vitest";
2-
import { getTextResponse, serverLogs } from "../../__test-utils__";
2+
import { getTextResponse, serverLogs, viteTestUrl } from "../../__test-utils__";
33

44
test("basic hello-world functionality", async () => {
55
expect(await getTextResponse()).toEqual("Hello World!");
@@ -10,3 +10,9 @@ test("basic dev logging", async () => {
1010
expect(serverLogs.errors.join()).toContain("__console error__");
1111
expect(serverLogs.errors.join()).toContain("__console warn__");
1212
});
13+
14+
test("receives the original host as the `X-Forwarded-Host` header", async () => {
15+
const testUrl = new URL(viteTestUrl);
16+
const response = await getTextResponse("/x-forwarded-host");
17+
expect(response).toBe(testUrl.host);
18+
});

packages/vite-plugin-cloudflare/playground/worker/src/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
export default {
2-
async fetch() {
2+
async fetch(request) {
3+
const url = new URL(request.url);
4+
5+
if (url.pathname === "/x-forwarded-host") {
6+
return new Response(request.headers.get("X-Forwarded-Host"));
7+
}
8+
39
console.log("__console log__");
410
console.warn("__console warn__");
511
console.error("__console error__");

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ export function getRouterWorker(miniflare: Miniflare) {
2222
}
2323

2424
export function toMiniflareRequest(request: Request): MiniflareRequest {
25+
// We set the X-Forwarded-Host header to the original host as the `Host` header inside a Worker will contain the workerd host
26+
const host = request.headers.get("Host");
27+
if (host) {
28+
request.headers.set("X-Forwarded-Host", host);
29+
}
2530
// Undici sets the `Sec-Fetch-Mode` header to `cors` so we capture it in a custom header to be converted back later.
2631
const secFetchMode = request.headers.get("Sec-Fetch-Mode");
2732
if (secFetchMode) {

0 commit comments

Comments
 (0)