Next.js Discord

Discord Forum

Multi-Subdomain Auth with Middleware and Authjs/NextAuth

Unanswered
English Shepherd posted this in #help-forum
Open in Discord
English ShepherdOP
I'm trying to get multi-subdomain auth working for my app. This is probably more of an Authjs question, but trying here just in case.

I have multiple subdomains working using a modified version of the middleware from this post (https://vercel.com/guides/nextjs-multi-tenant-application), pasted below.

I'm also using Authjs (v5). I have an auth-protected API route where I'm trying to get user information from Authjs using its wrapper function (the auth function that's returned when calling NextAuth), but nothing is coming through. This only happens when using the middleware; it works just fine without.

Any ideas how to investigate/debug here? Thanks in advance!

import "server-only";
import { NextRequest, NextResponse } from "next/server";

export const config = {
  matcher: [
    "/((?!api/|_next/|_static/|_vercel|[\\w-]+\\.\\w+).*)",
  ],
};

const middleware = async (req: NextRequest) => {
  const appHostname = process.env.NEXT_PUBLIC_APP_HOST.split("://")[1];

  const url = req.nextUrl;

  // Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
  let hostname = req.headers.get("host");
  const subdomain = hostname.replace(appHostname, "").replace(/\.$/, "");

  const searchParams = req.nextUrl.searchParams.toString();
  // Get the pathname of the request (e.g. /, /about, /blog/first-post)
  const path = `${url.pathname}${searchParams.length > 0 ? `?${searchParams}` : ""
    }`.replace(/\/$/, "");

  // rewrite root application to `/www` folder
  if (hostname === appHostname) {
    return NextResponse.rewrite(new URL(`/www${path}`, req.url));
  }

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

export default middleware;

2 Replies

English ShepherdOP
bump
English ShepherdOP
bump