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"
});
The reason that it only works for only one subdomain is that
next authby 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: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.homeordev.homeinstead oflocalhost). 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