AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Invalid URL When Returning A Relative Location Header In Middleware

Next.js middleware can return a response with a relative Location header (as allowed by HTTP spec), but the internal adapter passes this value directly to the NextURL constructor, which requires an absolute URL, causing an 'Invalid URL' error.

highConfidence 95%Next.jsAffected V15.1.0

Origin Analysis

In packages/next/src/server/web/adapter.ts, the Location header from the middleware response is extracted and passed to new NextURL(location) without providing a base URL. NextURL internally calls new URL(location), which throws for relative URLs.
1. Create a Next.js 15.1.0 project with middleware that returns a response containing a relative Location header, e.g., NextResponse.json with headers: { location: '/' } or NextResponse.redirect('/'). 2. Run the dev server and visit a route that triggers the middleware. 3. Observe the error 'Invalid URL' in the terminal or browser.

Fixing Code Block

Edge Case Audit

While this fix resolves relative URLs, it introduces a dependency on request.nextUrl which may reflect an internal URL behind a reverse proxy, potentially causing incorrect redirect targets if the middleware intends a different origin. Ensure that request.nextUrl correctly represents the external origin. Rollback recommendation: if this fix causes unexpected behavior, revert the change and use absolute URLs in middleware redirects as a temporary workaround.

Ecosystem Topology