Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NextResponse.redirect() behaves incorrectly when redirecting from subdomain route to apex domain route #75173

Open
bentron2000 opened this issue Jan 22, 2025 · 2 comments
Labels
Middleware Related to Next.js Middleware.

Comments

@bentron2000
Copy link

Link to the code that reproduces this issue

https://github.com/bentron2000/next-response-bug-report

To Reproduce

Set /etc/hosts:

127.0.0.1 example.test
127.0.0.1 foo.example.test

Install Packages:

npm i

Start Server:

npm run dev

Then Navigate to the following link and observe the result.
'http://foo.example.test:3000/shouldredirect'

Current vs. Expected behavior

When you navigate to the 'http://foo.example.test:3000/shouldredirect'
Middleware should select for this route and redirect to the apex domain '/login' page

Expected Result:
Redirect to : 'http://example.test:3000/login' -> 'Hooray - we redirected properly'

Actual Result:
Redirect to : 'http://foo.example.test:3000/login' -> 'Should not be redirected here'

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 24.2.0: Fri Dec  6 18:51:28 PST 2024; root:xnu-11215.61.5~2/RELEASE_ARM64_T8112
  Available memory (MB): 16384
  Available CPU cores: 8
Binaries:
  Node: 20.10.0
  npm: 10.8.1
  Yarn: 1.22.22
  pnpm: 9.15.0
Relevant Packages:
  next: 15.2.0-canary.19 // Latest available version is detected (15.2.0-canary.19).
  eslint-config-next: N/A
  react: 19.0.0
  react-dom: 19.0.0
  typescript: 5.7.3
Next.js Config:
  output: N/A

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

Middleware

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

next dev (local)

Additional context

Minimal demo of possible middleware NextResponse.redirect() Bug

Demonstrates that NextResponse.redirect is not obeying explicit urls when redirecting from a subdomain foo.example.test to the apex domain example.test

In this example, middleware has been set to catch a specific subdomain route and to redirect it to an explicitly set route on the apex domain
'http://foo.example.test:3000/shouldredirect' -> 'http://example.test:3000/login'

This does not happen - it redirects to the same path but on the subdomain.

To Reproduce

Set /etc/hosts:

127.0.0.1 example.test
127.0.0.1 foo.example.test

Install Packages:

npm i

Start Server:

npm run dev

Then Navigate to the following link and observe the result.
'http://foo.example.test:3000/shouldredirect'

Middleware should select for this route and redirect to the apex domain '/login' page

Expected Result:
Redirect to : 'http://example.test:3000/login' -> 'Hooray - we redirected properly'

Actual Result:
Redirect to : 'http://foo.example.test:3000/login' -> 'Should not be redirected here'

@github-actions github-actions bot added the Middleware Related to Next.js Middleware. label Jan 22, 2025
@bentron2000 bentron2000 changed the title NextResponse.redirect() fails when redirecting from subdomain route to apex domain route NextResponse.redirect() behaves incorrectly when redirecting from subdomain route to apex domain route Jan 22, 2025
@icyJoseph
Copy link
Contributor

I think there has been a fix related to this issue, #64604, but it requires setting a basePath IIRC, which is not ideal... somewhat related discussion here, #74732

@bentron2000
Copy link
Author

bentron2000 commented Jan 24, 2025

Thanks for the reply. Those links seem to pertain to page-based redirects.
Using redirect() from a page to redirect from a subdomain to the apex domain works as expected - likely due to the fixes you describe.

The issue however is within middleware. eg:
return NextResponse.redirect(new URL("http://example.test:3000/login"))

You reference providing a basepath - the only apparent way to do this is in the second argument to NextResponse.redirect which has the type:

interface ResponseInit extends globalThis.ResponseInit {
    nextConfig?: {
        basePath?: string;
        i18n?: I18NConfig;
        trailingSlash?: boolean;
    };
    url?: string;
}

however, providing:

return NextResponse.redirect(
          new URL("http://example.test:3000/login"),
          { nextConfig: { basePath: "http://example.test:3000/" } }
        );

has the same result.
No matter what I try, when the apex domain is the same, if the request comes in on a subdomain, the result is always to redirect to the subdomain. Never to the apex domain.
Redirecting to an entirely different domain works as expected - so this must be some bug or edge case that is not handled properly.

For inline reference, here is the middleware.ts

import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: [
    /*
     * Match all paths except for:
     * 1. /api routes
     * 2. /_next (Next.js internals)
     * 3. /_static (inside /public)
     * 4. all root files inside /public (e.g. /favicon.ico)
     */
    "/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)",
  ],
};

export default async function middleware(req: NextRequest) {
  const host = req.headers.get("host") || "";
  const [subdomain, ...rest] = host.split(".");
  const hasSubdomain = rest.length >= 2;

  // check if this came in on a subdomain
  if (hasSubdomain) {
    console.log({ subdomain, nextUrl: req.nextUrl });

    // specifically redirect the "shouldredirect" subdomain as a demonstration
    if (req.nextUrl.pathname.startsWith("/shouldredirect")) {
      // explicitly redirect to the login page with a fully defined URL

      const rootLoginPage = new URL("http://example.test:3000/login");

      console.log(
        `redirecting to root login page - ${rootLoginPage.toString()}`
      );

      return NextResponse.redirect(rootLoginPage); // <-- actually redirects to http://foo.example.test:3000/login
    }

    // otherwise, rewrite the subdomain to the /[domain] dynamic route
    return NextResponse.rewrite(
      new URL(`/${subdomain}${req.nextUrl.pathname}`, req.url)
    );
  }

  // handle all other requests
  return NextResponse.next();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Middleware Related to Next.js Middleware.
Projects
None yet
Development

No branches or pull requests

2 participants