Next.js Discord

Discord Forum

Redirect from subdomain to root domain via middleware

Unanswered
West African Lion posted this in #help-forum
Open in Discord
West African LionOP
Hi guys.

using Next 13 pages.

So I have a blogging app users can have subdomains, the way I handle them is via rewrites in the middleware (see attached code snippet), what I want is if the article doesn't belong to the subdomain they get redirected to
rootdomain.com/articleId

current behaviour:

foo.rootdomain.com/article-that-doesn't-belong-to-foo --> can access

the behaviour I want:

foo.rootdomain.com/article-that-doesn't-belong-to-foo --> redirect to rootdomain.com/author/username-of-author/articleId

this is my current setup, this causes an infinite redirect and I can't see the subdomain being removed from the url

thank you in advance.

middleware.ts
export async function middleware(req: NextRequest) {
  const url = req.nextUrl.clone();
  if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes("_next")) return;
  const host = req.headers.get('host');
  const subdomain = getValidSubdomain(host);

  if (subdomain) {
    const user = await getUserByUsername(subdomain);

    if (user) {
      const userArticles = await getUserArticles(user.username);

      // rewrite
      if (url.pathname.includes("/author/")
        && userArticles?.find((article) => article.slug === url.pathname)
      ) {
        url.pathname = `/author/${subdomain}${url.pathname.replace("/author/", "")}`;
        return NextResponse.rewrite(url);
      }
      if (url.pathname === "/") {
        url.pathname = `/author/${subdomain}`;
        return NextResponse.rewrite(url);
      }
      if (userArticles?.find((article) => article.slug === url.pathname)) {
        // article actually belongs to the user
        return NextResponse.rewrite(url);
      }
      // article does not belong to the user redirect to root domain
        url.host = env.NEXT_PUBLIC_ROOT_DOMAIN! + url.pathname;
        return NextResponse.redirect(url);
    }
  }
  return NextResponse.next();
}

0 Replies