vercel/next.js

Invalid URL when returning a relative location header in middleware

blairmcalpine opened this issue · 0 comments

Link to the code that reproduces this issue

https://github.com/blairmcalpine/next-invalid-url-repro

To Reproduce

Clone the repo
Run npm i
Run npm dev
Visit localhost:3000/broken.
See the error message "Invalid URL".

Current vs. Expected behavior

I expect to be properly redirected to the home page, but instead there is an error.

This is because we get the location header from the response from middleware (which is allowed to be relative), and pass it directly into the NextURL class:

const redirect = response?.headers.get('Location')

This, under the hood, calls new URL with that value (and no baseUrl), causing the error.

The fix here would be to append the base url to the location variable here before passing it to new NextURL.

To be clear here as well, the repro works here by just explicitly returning a NextResponse.json in middleware. While this could be fixed by just using NextResponse.rewrite in this case, this doesn't work in the general case where we don't necessarily know if it's a redirect or not (and to where we are redirecting).

Provide environment information

Node.js v22.11.0

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.6.0: Wed Jul 31 20:49:39 PDT 2024; root:xnu-10063.141.1.700.5~1/RELEASE_ARM64_T6000
  Available memory (MB): 32768
  Available CPU cores: 10
Binaries:
  Node: 22.11.0
  npm: 10.9.0
  Yarn: 4.4.0
  pnpm: N/A
Relevant Packages:
  next: 15.1.0 // Latest available version is detected (15.1.0).
  eslint-config-next: 15.1.0
  react: 19.0.0
  react-dom: 19.0.0
  typescript: 5.7.2
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Middleware, Navigation, Runtime

Which stage(s) are affected? (Select all that apply)

next dev (local), next start (local), Vercel (Deployed), Other (Deployed)

Additional context

No response