Skip to content

[BUG] Location header uses absolute url instead of relative url #809

@ericmatthys

Description

@ericmatthys

Describe the bug

When using middleware to redirect to a different URL (https://nextjs.org/docs/app/guides/redirecting#nextresponseredirect-in-middleware), the Location header is always absolute. When deployed to Vercel or running dev locally, the Location header can be relative.

Cloudflare or opennextjs-cloudflare preview: location: https://example.workers.dev/foo
Vercel or next dev: location: /foo

This has a couple effects:

  • Automated tests that are asserting on the location header are not consistent between local and deployment.
  • When using a worker to proxy requests from preview urls with custom domains to workers.dev urls, the location header is using the workers.dev url causing a redirect away from the custom domain.

Steps to reproduce

In middleware, perform a redirect like so:

middleware.ts

export function middleware(request: NextRequest) {
  const url = request.nextUrl.clone();

  if (url.pathname.startsWith('/foo') {
    return NextResponse.next();
  }

  url.pathname = '/foo';
  return NextResponse.redirect(url);
}

Request the site and inspect the location header of the 307 redirect response.

Expected behavior

The location header should match local dev and Vercel behavior, using a relative url when possible.

@opennextjs/cloudflare version

1.5.1

Wrangler version

4.24.1

next info output

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.6.0: Mon Jul 29 21:14:30 PDT 2024; root:xnu-10063.141.2~1/RELEASE_ARM64_T6000
  Available memory (MB): 65536
  Available CPU cores: 10
Binaries:
  Node: 22.17.0
  npm: 10.9.2
  Yarn: N/A
  pnpm: 8.15.9
Relevant Packages:
  next: 14.2.30 // An outdated version detected (latest is 15.4.3), upgrade is highly recommended!
  eslint-config-next: 14.2.29
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.8.3
Next.js Config:
  output: N/A
 ⚠ An outdated version detected (latest is 15.4.3), upgrade is highly recommended!
   Please try the latest canary version (`npm install next@canary`) to confirm the issue still exists before creating a new issue.

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriage

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions