I’m working on implementing authentication using AuthJS (NextAuth) in a Next.js app. I want the session and CSRF cookies to be accessible across subdomains (e.g., *.localhost:3000
) as well as the main domain (localhost:3000
).
I configured the cookies like this in authOptions
:
cookies: {
sessionToken: {
name: "next-auth.session-token",
options: {
domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN || ".alchmy.com", // Set cookie for all subdomains
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
},
},
csrfToken: {
name: "next-auth.csrf-token",
options: {
domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN || ".alchmy.com",
httpOnly: false,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
},
},
}
My .env
is set like this:
NEXT_PUBLIC_COOKIE_DOMAIN=.localhost
The issue is that cookies are attaching correctly to localhost:3000
, but they are inaccessible when I try to access any subdomain like subdomain.localhost:3000
. The browser is not sending the cookies in requests to the subdomains.
I configured the domain
for both sessionToken
and csrfToken
cookies to be .localhost
in the environment file. I expected this to allow the cookies to be shared across all subdomains, but this isn’t working as intended.
I also tried various cookie options like changing sameSite
, but I keep getting MissingCSRF
errors on the login page after login.
How can I make the cookies accessible on subdomains when using NextAuth?