platforms icon indicating copy to clipboard operation
platforms copied to clipboard

Router.push Shallow writing wrong URL using Middleware NextResponse.rewrite(url)

Open minardimedia opened this issue 2 years ago • 0 comments

I am using the platform code to write a multitenat application.

When I perform a shallow router push in one of the subdomain URLs the url writes wrong extra information

Working in localhost with subdomains

Original URL http://casablanca.nomadtest.com:3001/room/20991d5b-c321-4b75-9c01-4fc85e7a4c3d

Run the Router.push

          router.push(
            {
              query: {
                site: router.query.site,
                id: router.query.id,
                start_date: "12-12-2022",
              },
            },
            undefined,
            {
              shallow: true,
            }
          );

This provoke a whole page hard reload

Resulting URL http://casablanca.nomadtest.com:3001/_sites/casablanca/room/20991d5b-c321-4b75-9c01-4fc85e7a4c3d?start_date=12-12-2022

It add extra "_sites/casablanca/"

Expected URL: http://casablanca.nomadtest.com:3001/room/20991d5b-c321-4b75-9c01-4fc85e7a4c3d?start_date=12-12-2022

Avoid page reload

Here is the middleware handling the rewrite

export default function middleware(req: NextRequest) {
  const url = req.nextUrl.clone();
  const { pathname } = req.nextUrl;
  const hostname = req.headers.get("host");
  const currentHost = hostname!.replace(`.nomadtest.com:3001`, "");

  if (pathname.startsWith(`/_sites`)) {
    return new Response(null, { status: 404 });
  }

  if (!pathname.includes(".") && !pathname.startsWith("/api")) {
    if (currentHost === "host") {
      url.pathname = `/host${pathname}`;
      return NextResponse.rewrite(url);
    } else if (hostname === "nomadtest.com:3001") {
      return NextResponse.rewrite(url);
    } else {
      url.pathname = `/_sites/${currentHost}${pathname}`;
      return NextResponse.rewrite(url);
    }
  }
  return NextResponse.rewrite(url);
}

minardimedia avatar Jun 02 '22 00:06 minardimedia