Skip to main content

sometechblog.com

Enable NextAuth to Work Across Subdomains

Table of Contents

By default NextAuth authenticates the domain provided by the NEXTAUTH_URL environmental variable and if it is on a sub domain like www.example.org also all domains below www like subdomain.www.example.org or subdomain.subdomain.example.org. It is often smart to make the domain authentication work across all sub domains to avoid restrains when branching out API services or deploying on sub domains.

To do this you need to set the cookie domain to root wildcard. If my web app is deployed on https://www.sqlai.ai/ then the root domain is sqlai.ai. The wildcard cookie domain that can be accessed on all subdomains is .sqlai.ai. The .www.sqlai.ai is only available on www.sqlai.ai and its sub domains.

Customize the cookie domain in the [...nextuaht].ts file by adding:

const { hostname } = new URL(process.env.NEXTAUTH_URL);
// This doesn't work for *.co.uk domains and it might be easier to simply write the root domain: sqlai.ai
const ROOT_DOMAIN = hostname.split('.').reverse().splice(0, 2).reverse().join('.');
const isSecure = process.env.NODE_ENV !== 'development';

export default NextAuth({
  //... omitted for brevity
  cookies: {
    sessionToken: {
      name: isSecure ? `__Secure-next-auth.session-token` : `next-auth.session-token`,
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        domain: `.${ROOT_DOMAIN}`, // Note the dot
        secure: isSecure,
      },
    },
  },
});

# References