platforms icon indicating copy to clipboard operation
platforms copied to clipboard

Adding NextAuth

Open arepp23 opened this issue 1 year ago • 0 comments

Based on this tutorial, you need to add NextAuth to a Next.js app via the middlware.ts file.

They recommend setting up the middleware.ts like this:

import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
 
export default NextAuth(authConfig).auth;
 
export const config = {
  // https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
  matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
};

This will not work with the multi-tenant middleware since it already has an export default.

export default async function middleware(req: NextRequest) {
  const url = req.nextUrl;

  // Get hostname of request (e.g. demo.vercel.pub, demo.localhost:3000)
  let hostname = req.headers
    .get("host")!
    .replace(".localhost:3000", `.${process.env.NEXT_PUBLIC_ROOT_DOMAIN}`);

  // special case for Vercel preview deployment URLs
  if (
    hostname.includes("---") &&
    hostname.endsWith(`.${process.env.NEXT_PUBLIC_VERCEL_DEPLOYMENT_SUFFIX}`)
  ) {
    hostname = `${hostname.split("---")[0]}.${
      process.env.NEXT_PUBLIC_ROOT_DOMAIN
    }`;
  }
...

What is the recommended pattern here for using NextAuth in middleware while also having the custom middleware for the subdomains?

arepp23 avatar Dec 15 '23 03:12 arepp23