Skip to content

Commit 9ab86d4

Browse files
authored
fix: host not included in route handler urls (#234)
1 parent 6e51aa2 commit 9ab86d4

File tree

4 files changed

+20
-2
lines changed

4 files changed

+20
-2
lines changed

.changeset/short-cats-kneel.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@opennextjs/cloudflare": patch
3+
---
4+
5+
fix: host not included in route handler urls
6+
7+
Next.js was unable to re-construct the correct URLs for the request in a route handler due to being unable to retrieve the hostname. This was due to the internal Next.js option `trustHostHeader` being disabled in OpenNext when there is external middleware - this option is needed for the Next.js server in our environment.

examples/api/app/api/request/route.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { NextRequest } from "next/server";
2+
3+
export const GET = (request: NextRequest) => {
4+
return new Response(JSON.stringify({ nextUrl: request.nextUrl.href, url: request.url }));
5+
};

examples/api/e2e/base.spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,10 @@ test("sets environment variables from the Next.js env file", async ({ page }) =>
3535
const res = await page.request.get("/api/env");
3636
await expect(res.json()).resolves.toEqual(expect.objectContaining({ TEST_ENV_VAR: "TEST_VALUE" }));
3737
});
38+
39+
test("returns correct information about the request from a route handler", async ({ page }) => {
40+
const res = await page.request.get("/api/request");
41+
// Next.js can fall back to `localhost:3000` or `n` if it doesn't get the host - neither of these are expected.
42+
const expectedURL = expect.stringMatching(/https?:\/\/localhost:(?!3000)\d+\/api\/request/);
43+
await expect(res.json()).resolves.toEqual({ nextUrl: expectedURL, url: expectedURL });
44+
});

packages/cloudflare/src/cli/build/open-next/createServerBundle.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,7 @@ async function generateBundle(
182182
target: /core(\/|\\)util\.js/g,
183183
deletes: [
184184
...(disableNextPrebundledReact ? ["requireHooks"] : []),
185-
...(disableRouting ? ["trustHostHeader"] : []),
186-
...(!isBefore13413 ? ["requestHandlerHost"] : []),
185+
...(isBefore13413 ? ["trustHostHeader"] : ["requestHandlerHost"]),
187186
...(isAfter141 ? ["experimentalIncrementalCacheHandler"] : ["stableIncrementalCache"]),
188187
],
189188
}),

0 commit comments

Comments
 (0)