Next.js Discord

Discord Forum

Multiple dynamic page rewriting with middleware

Answered
Hamiltonstövare posted this in #help-forum
Open in Discord
HamiltonstövareOP
We have a platform where users can create websites. All websites have their own subdomain connected to our domain e.g. userWebsite.ourWebsite.com. It is fairly easy to have one page solution, we do it by rewriting by /_sites/subdomain route (file: /pages/_sites/[[..subdomain]].tsx).

We want to implement multiple pages, the drawbacks are:
We'd have to remove the path matcher on the middleware:
export const config = {
  matcher: ["/"],
}


Sure! we did that and added whitelistedPaths instead to ignore the unwated paths;
// TODO: Remove this when we have a proper solution.
  // I removed the path matcher config so that user websites can have multiple pages
  const whitelistedPaths = [
    "/api",
    "/_next",
    "/favicon.ico",
    "/robots.txt",
    "/sitemap.xml",
    "/manifest.webmanifest",
    "/assets",
    "/browserconfig.xml",
    "/sitemap-0.xml",
    "/_sites",
    "/embed",
    "/join",
    "/404",
    "/redirect",
    "/verify",
    "/payments",
    "/collection-generator",
    "/metadata",
    "/mint-button",
    "/website",
    "/whitelist",
    "/pricing",
    "/terms",
    "/privacy",
  ];
  if (whitelistedPaths.some((path) => pathname.startsWith(path))) {
    return res;
  }


Now it's able to go to the about page http://i6sf7a5s.localhost:3000/about but if I type any route on the whitelistedPaths it goes to that page because I have a /pages/[[...index]].tsx file, that handles some of the routes on whitelistedPaths array.

PS: not using app directory
Answered by Hamiltonstövare
Fixed:
Just had to add a system path check
const isSystemPath = systemPaths.some((path) => pathname.startsWith(path));

  if (isSubdomain && !isSystemPath) {
    const subdomain = host?.slice(0, host.indexOf("."));
    if (subdomain === "www") return res;
    url.pathname = `/_sites/${subdomain}${url.pathname}`;
    return NextResponse.rewrite(url);
  }
View full answer

1 Reply

HamiltonstövareOP
Fixed:
Just had to add a system path check
const isSystemPath = systemPaths.some((path) => pathname.startsWith(path));

  if (isSubdomain && !isSystemPath) {
    const subdomain = host?.slice(0, host.indexOf("."));
    if (subdomain === "www") return res;
    url.pathname = `/_sites/${subdomain}${url.pathname}`;
    return NextResponse.rewrite(url);
  }
Answer