vercel / platforms

A full-stack Next.js app with multi-tenancy and custom domain support. Built with Next.js App Router and the Vercel Domains API.
https://app.vercel.pub
5.59k stars 728 forks source link

Exemple? #432

Open lucasdesouza-dev opened 3 days ago

lucasdesouza-dev commented 3 days ago
          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 https://github.com/vercel/platforms/issues/329#issuecomment-2182022845

CrutchTheClutch commented 3 days ago

Seems people run into this fairly frequently when first starting with the platforms starter kit. +1 a proper example should be added