Skip to content

Exemple?Β #432

Open
Open
@lucasdesouza-dev

Description

          May be a little convoluted but I was just trying to do something like this.  This is what I came up with as a workaround for local dev and it seems to work.  Basically, I just treated the root domain as a subdomain when developing locally.

I have some variables define that determine the domain I am targeting and will later use this in my middleware to filter where I want things to be routed.

export const ROOT_DOMAIN = `${ROOT}.com`;

export const ROOT_HOSTNAMES = new Set<string>([
  ROOT_DOMAIN,
  "root.localhost:3000",
]);

export const APP_DOMAIN =
  process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
    ? `https://app.${ROOT_DOMAIN}`
    : "http://localhost:3000";

export const APP_HOSTNAMES = new Set<string>([
  `app.${ROOT_DOMAIN}`,
  "localhost:3000",
]);

The key here is making sure the root domain is treated as a subdomain root.localhost:3000 and the subdomain we are targeting is treated as the root localhost:3000.

Next, my middleware function uses the previously defined variables to determine our routes. I have the folders setup as the actual domain names for clarity here

export function middleware(req: NextRequest) {
  const { domain, path, key } = parse(req);

  // rewrite app to `/app.domain.com` folder
  if (APP_HOSTNAMES.has(domain)) {
    return NextResponse.rewrite(
      new URL(`/app.domain.com${path === "/" ? "" : path}`, req.url),
    );
  }

  // rewrite admin to `/admin.domain.com` folder
  if (ADMIN_HOSTNAMES.has(domain)) {
    return NextResponse.rewrite(
      new URL(`/admin.domain.com${path === "/" ? "" : path}`, req.url),
    );
  }

  // rewrite root to `/domain.com` folder
  if (ROOT_HOSTNAMES.has(domain)) {
    return NextResponse.rewrite(
      new URL(`/domain.com${path === "/" ? "" : path}`, req.url),
    );
  }

  // rewrite everything else to `/[domain]/[slug] dynamic route
  return NextResponse.rewrite(new URL(`/${domain}${path}`, req.url));
}

Lastly, we can now go target the standard localhost:3000 and http://localhost:3000/api/auth/callback/google for our Google auth!

Originally posted by @CrutchTheClutch in #329 (comment)

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions