How do I get a NextAuth user session on subdomains?

45 views Asked by At

I have an authorization page that is located on the domain auth.localhost:3000/login

But the problem is that after the user is logged in, I can't get data about him if I switch to another subdomain,

Example:

  • auth.localhost:3000 - ✅ (authenticated)
  • any.localhost:3000 - ❌ (not authenticated)
  • localhost:3000 - ❌ (not authenticated)
auth.ts

"next-auth": "5.0.0-beta.16"
"next": "14.1.4"


import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import { PrismaAdapter } from "@auth/prisma-adapter";
import prisma from "./prisma";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  providers: [GitHub],
  adapter: PrismaAdapter(prisma),
  session: { strategy: "jwt" },
  redirectProxyUrl: "http://auth.localhost:3000/api/auth"
});
1

There are 1 answers

4
Arash Jahan Bakhshan On BEST ANSWER

The reason that it only works for only one subdomain is that next auth by default sets the cookies on the domain that the signIn has performed on. To change the default behavior and give it a custom domain (e.g. domain with empty subdomain which means all subdomains .my-site.com) while using next auth version 5 we should config the cookies' options like so:

const nextAuthUrl = process.env.NEXTAUTH_URL

NextAuth({
    cookies: {
        sessionToken: {
            name: `${nextAuthUrl.startsWith('https://') ? "__Secure-": ""}next-auth.session-token`,
            options: {
                domain: nextAuthUrl === "localhost" ? "." + nextAuthUrl : "." + new URL(nextAuthUrl).hostname, // support all subdomains
                httpOnly: true,
                sameSite: 'lax',
                path: '/',
                secure: nextAuthUrl.startsWith('https://'),
            }
        }
    }
})

You might also need to config other cookies as well depending on your use case. you can read more about it in the official documentation: https://next-auth.js.org/configuration/options#cookies

EDIT:

I searched more in next auth's github discussions and looks like some people already had this issue. The solution is here: https://github.com/nextauthjs/next-auth/discussions/4089#discussioncomment-2297717

In short: You should set another dummy domain like a real one instead of just localhost (e.g. localhost.home or dev.home instead of localhost). Note that it's better to use a unique domain so it won't be a problem in the future if you open a website that its domain or its API's domain is common with your local host name