Wednesday, 21 June 2023

NextAuth with Wildcard / Custom Domains

I have a NextJS application. It's a multi-tenant SaaS application.

The app provides each customer with the option to use a subdomain on our site or to map their custom domain vis CNAME.

I want to allow our customers to allow their employees to login on their subdomain site or custom domain.

export const authOptions: NextAuthOptions = {
  // Configure one or more authentication providers
  providers: [
     EMAIL PROVIDER
    // ...add more providers here
  ],
  pages: {
    signIn: `/login`,
    verifyRequest: `/verify`,
  },
  adapter: PrismaAdapter(prisma),
  callbacks: {

  },
  cookies: {
    sessionToken: {
      name: 'next-auth.session-token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        domain: process.env.NODE_ENV === 'production' ? '.mysaas.com' : undefined,
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false
      }
    },
    callbackUrl: {
      name: 'next-auth.callback-url',
      options: {
        sameSite: 'lax',
        path: '/',
        domain: process.env.NODE_ENV === 'production' ? '.mysaas.com' : undefined,
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false
      }
    },
    csrfToken: {
      name: 'next-auth.csrf-token',
      options: {
        sameSite: 'lax',
        path: '/',
        domain: process.env.NODE_ENV === 'production' ? '.mysaas.com' : undefined,
        secure: process.env.NODE_ENV && process.env.NODE_ENV === 'production' ? true : false
      }
    }
  }  
}

export default NextAuth(authOptions)

With the above [...nextauth] file, I'm able to make it work with subdomains as I'm using '.mysaas.com' for domain cookie.

However, it doesn't work with a custom domain mapped to a subdomain? How can I achieve that?

If I can set the cookie domain dynamically so that I can dynamically set the domain to the actual domain, then it will work. Like instead of .mysaas.com, if I could set it to .mycustomdomain.com, if the login page is called from this custom domain, then the problem gets resolved.

However, I cannot find a way to set this cookie domain dynamically. Any help is appreciated.



from NextAuth with Wildcard / Custom Domains

No comments:

Post a Comment