platforms icon indicating copy to clipboard operation
platforms copied to clipboard

Custom Domain Bindings

Open shawnmclean opened this issue 8 months ago • 1 comments

How would this look if we were to add custom domains following this guide: https://vercel.com/guides/nextjs-multi-tenant-application

Would we have to change the middleware to check the full domain or is there some other recommendation?

shawnmclean avatar May 23 '25 18:05 shawnmclean

@shawnmclean

Perhaps someone else will elaborate better, here's a general idea of how to do it:

middleware.ts

export async function middleware(req: NextRequest) {
  const url = req.nextUrl;
  const hostname = req.headers.get("host").replace(".localhost:3000", `.${ROOT_DOMAIN_VARIABLE}`);
  const pathname = url.pathname;

  // rewrite to your homepage if it matches the root domain or a custom domain assigned to home

  if (hostname === "localhost:3000" || hostname === ROOT_DOMAIN_VARIABLE || hostname === VERCEL_PROJECT_URL) {
     return NextResponse.rewrite(new URL(`/home${pathname === "/" ? "" : pathname}`, url));
  }

  // rewrite everything else to /[domain]
  return NextResponse.rewrite(new URL(`/${hostname}${pathname === "/" ? "" : pathname}`, url));
}

FOLDER STRUCTURE

/app
  /[domain]  <--- catch all custom domain stuff here
  /home <-- your fancy homepage

INSIDE DOMAIN FOLDER (example) /app/[domain]/layout.tsx

export async function Layout({ params: layoutParams }) {
  const params = await layoutParams;
  const domain = params.domain; // your custom domain 

  ...
}

itstrevinooo avatar Jun 19 '25 00:06 itstrevinooo