-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Need to set NEXTAUTH_URL dynamically as an Option for multi-domain/multi-tenant use #600
Comments
Server has a Lines 47 to 50 in 12a5d6b
JWT. GetToken can be custom though: Lines 94 to 103 in 8115a7c
And, for the client: Lines 24 to 26 in 8115a7c
These are the references I found. @iaincollins I can try to fork and attempt a hack on my side, since I really need to solve this. If you can advise how to go about it, it would be awesome. It seems you intend to refine/refactor this at some point, as stated above. Above three are the only references I found. Any help is really appreciated. |
Okay, so I managed to fork and make server-side work! Looking into the client side now... I added to server: const { origin } = absoluteUrl(req)
// @todo refactor all existing references to site, baseUrl and basePath
const parsedUrl = parseUrl(process.env.NEXTAUTH_URL || origin || process.env.VERCEL_URL) and export const absoluteUrl = (req) => {
var protocol = "https:"
var host = req
? req.headers["x-forwarded-host"] || req.headers["host"]
: window.location.host
if (host.indexOf("localhost") > -1 || host.indexOf(".local") > -1) {
protocol = "http:"
}
return {
protocol: protocol,
host: host,
origin: protocol + "//" + host,
}
} |
Hi Sharad, If you are seeing this error there is likely problem with your build process or how you are linking to the libraries. You'd need to post and link to the repo before we can help with that. Regarding the wider question of supporting domains dynamically, this is something we don't support currently. I don't have an update on this I'm ready to share right now, but I hope there will be an update on this at some point in the coming weeks. |
Thanks Iain, yes I am trying to get my head around this. I also started my own Adapter, based on your prisma adapter... to support multi-tenancy in database. Pretty much everything you have as-is, plus associating users with a Business (tenant) record. Excellent work with next-auth. So helpful. |
We really need this as well, as we have a multi-tenant Next app in the works. It seems like you could take in a callback function in the |
Our application is multi-tenant as well. We also need(ed) this feature. |
I also need this to be able to properly setup salesforce as a custom oAuth2 provider:
There are cases where the user will need to specify their "subdomain" in order to be able to login. |
I've tried to address this here: skilesare@86ea3de It may need some changes....and I only really focused on the session call back because I needed to get some data based on the domain in the session, but the pattern should be easy to follow for the other callbacks. Basically the request (req) just needs to be passed to these callbacks so that you can key in on the domain/sub domain. The other potential gotcha is the http vs https so if anyone has a suggestion for that, let me know. If any one wants to walk me through how to get this set up so that it can eventually be pulled in, let me know as well...haven't contributed to projects this big before and don't want to step on any toes. |
Our application is multi-tenant as well. We also need(ed) this feature. I would like to be able to simply set the redirect_url in the provider options |
One good reason to think to support multi-tenant is that nex-auth is likely to be deployed on vercel. On vercel each deployment has several domains (a lot more if the user defined aliases). Since this is a project for next.js, supporting Vercel looks natural to me. |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
To anyone reading this, please stop +1 issues, it is really not helpful, and creates noise. 😕 If you have nothing constructive to add, do click "👍" on the original comment instead. |
Hi there! It looks like this issue hasn't had any activity for a while. It will be closed if no further activity occurs. If you think your issue is still relevant, feel free to comment on it to keep it open. (Read more at #912) Thanks! |
Could someone please confirm that this new option resolves this issue? https://next-auth.js.org/configuration/options#nextauth_url_internal |
Hey @balazsorban44 I cannot think or figure out how https://next-auth.js.org/configuration/options#nextauth_url_internal would resolve handling Do you think this may be possible with BTW I started some work regarding |
I see, thanks for the update! To be honest, I haven't really looked into this use-case yet, so I wasn't entirely sure what was needed. So I am not going to close this for now. |
@balazsorban44 - is there a place to talk (besides GitHub, like a Slack/Discord) for NextAuth community? Also, could you point me out to docs on how to best test, build, and package my solution to do something in my current environment? I was thinking of building the fork and just upload it to GitHub packages. |
Either GitHub packages or npm would do. We use semantic release for automatic releases based on commit messages. The best place for community discussions are here in issues or alternatively discussions, as these are the public places where everyone can see any part of the discussion. |
I already posted a |
Hi @Robert-OP thanks for your work. I don't see a PR for these changes in this repo, did you opened it? |
For the whitelisting couldn't be inferred from i18n config in next? https://nextjs.org/docs/advanced-features/i18n-routing ? I guess this list is not useful for the Vercel preview use case but as @thulstrup commented could be a regexp check (option 2) So whitelisting could be in these 2 ways:
I never worked with Vercel but I guess setting |
Hey @andresgutgon hope you are well! I didn't open a PR because the work is not finished yet, I didn't add the whitelisting of domains and I see that #969 (comment) it's not that of a good idea at least for Vercel. The solution above works, but I think still needs a review from the |
Sorry but I'm really confused how a major issue like this is still unresolved in 2 years, it basically makes this lib unusable. Is there anything I'm missing ? Am I just well understanding that I shouldn't be using this lib unless I choose to host it on Vercel ? Is this real ? |
so much about open source... more like vendor-locked source I know what hosting I MUST not use EDIT: it's your right to do so, just be clear & open about it |
After spending a lot of time to find the right solution using Next Auth, I decided to use something else. NextAuth is really cool, but as soon as you need something more custom or advanced, it becomes clear that you can't really do it easily. What I've done, if anyone are looking for a solution, I ended using the amazing iron-session library, which essentially gives you all the low-level tools to achieve something really powerful. I'm now having a multi tenant app, working across multiple subdomain and domain names using the same code, it's not impossible but require more thoughts! Good luck to everyone and thanks to the next auth team, the library is incredible in many many ways ;) |
@Rieranthony Are using Next.js v13.x with iron-session v8-alpha package for your multi-tenant solution? |
I'm using v8 with a custom implementation :) |
As a newbie to NextJS, i was surprised that this issue which is important yet no fix in place. I spent around 2 days to understand and figure out the way to add fix. I did the following code fix and it started allowing for multi-domain/multi-tenant. next-auth/packages/next-auth/src/utils/detect-origin.ts Lines 2 to 9 in f3c64a8
|
Hi @rajat1saxena. The thread is reused for multiple requests and it swaps between the calls whenever you use promises. |
I don't know if this helps someone, but the below code works for me. I am using next:
export const authOptions = (req: NextApiRequest): NextAuthOptions => {
// Need to ts-ignore this because the type `NextApiRequest` doesn't have the `get` method
// And we need the `get` method to get the hostname.
// @ts-ignore
const hostname = req.headers.get("host");
return {
providers: [...],
pages: {...},
session: { strategy: "jwt" },
cookies: {
sessionToken: {
name: `${VERCEL_DEPLOYMENT ? "__Secure-" : ""}next-auth.session-token`,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
// This is what works for me
domain: hostname.includes("localhost:3000") ? undefined : hostname,
secure: VERCEL_DEPLOYMENT,
},
},
},
callbacks: {...},
};
};
import { authOptions } from "@/lib/auth";
import { type NextApiResponse, type NextApiRequest } from "next";
import NextAuth from "next-auth";
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
return await NextAuth(req, res, authOptions(req));
};
export { handler as GET, handler as POST }; Note: Here NextAuth takes only |
"next": "^13.4.12", Following the Custom Initialization docs: https://authjs.dev/guides/basics/initialization and some other suggested stuff above I found a way to change
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
const { host } = req.headers;
//that worked for me
process.env.NEXTAUTH_URL = /localhost/.test(host || '')
? `http://${host}`
: host;
const config = await NextAuth(req, res, {
providers: [],
events: {},
callbacks: {}
} Not sure if it's the best approach, but it works on a scenario where the Github actions trigger a k8s deployment after opening a PR. Usually those deployments have a PR id attached to his address, something like: https://473-my-app.domain.com where |
I'm using I had to dynamically setup my cookie though in const authOptions = (request: NextApiRequest) => {
const useSecureCookies = process.env.NEXTAUTH_URL?.startsWith('https://') ?? !!process.env.AUTH_TRUST_HOST;
const cookiePrefix = useSecureCookies ? '__Secure-' : '';
const cookieDomain = useSecureCookies ? new URL(`http://${request.headers.host}`).hostname : null;
return {
...
cookies: {
sessionToken: {
name: `${cookiePrefix}next-auth.session-token`,
options: {
httpOnly: true,
sameSite: 'lax',
path: '/',
secure: useSecureCookies,
...(cookieDomain && { domain: cookieDomain })
}
}
},
...
} satisfies AuthOptions;
};
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
return NextAuth(req, res, authOptions(req));
} Anyone doing something similar in production and share any experience or insight? Also, why is multi-tenancy seemingly ignored by the NextAuth team even though it is functionally almost there? A mention in the doc acknowledging that multi-tenancy needs exist would be deeply appreciated. Going through 100+ comments over 3 years about this topic with no clear solution. Closed PRs:
|
Its not ignored, its support was deliberately removed to not have to consider ways to make it secure. Time spent researching how to get multi tenancy to work is probably better spent looking for alternatives. |
Forgive my assumption, thx for the context. I totally get multi-tenancy exponentiates complexity especially with a security product. I just wanted to explore the extensibility of NextAuth before deciding to abandon it. Honestly though, we prefer to continue to invest and contribute to it since it’s such a great foundation. Would something simple as converting I’m hoping for a little bit more guidance or insight on how and where the community can jump in. Possibly this can be a guide that lives outside the core offerings like the approach of role-based access control. |
I have faced the same issue but I have found a solution which was working fine for me by just updating the existing .env as follows :
|
where have AUTH_TRUST_HOST env setting? i can not find doc at next-auth |
The problem with AUTH_TRUST_HOST is that it doesn't respect basePath option of nextjs. And it's because parse-url uses defaultUrl in when AUTH_TRUST_HOST is
|
it is big problem , because NEXTAUTH_URL is for client side url, and client side url could be multi domain, it would be cause wrong domain redirect , so baseUrl should not be static variable , or maybe set a option in authOptions to change baseUrl
|
@wildfrontend I see there is quite big refactor in v5 regarding this. I was referring to v4. The parse-url is gone and instead I see:
Also I was talking about backend api/auth/providers not respecting basePath option and generating callback and redirect url without basePath. If your issue is on client side. You can get basePath from runtime config in _app.tsx:
in next.config.js you can set basePath from env param and also expose same value for runtime config (used in _app.tsx - as above)
|
Very ugly workaround for v4 basePath issue when AUTH_TRUST_HOST is true: Since req.origin is set by toInternalRequest function (detectOrigin) reading x-forwarded-host header and then req.origin is used in parseUrl, but since x-forwarded-host doesn't contain any paths, we need to add it, so parseUrl respects basePath. pages\api\auth[...nextauth].ts
|
Hey guys, (@mauron85, @wildfrontend) https://www.skcript.com/blog/how-to-build-multi-tenant-auth-nextjs |
Any workaround for |
|
@balazsorban44 Given the fact that this issue is by far the most upvoted one and was opened three years ago, I would like to kindly ask if it is possible to get a bit more attention? |
Vercel published a multi-tenant |
Same question on the v5 front, trying to accomplish this and the NextAuth default export no longer accepts the |
Short Answer: It's not supported. Some devs may find a work around but if you don't know what you're doing then please look for an alternative option. I wasted a lot of time looking for it and, in the end, had to look for an alternative option. Clerk Auth supports it otherwise go for a custom auth solution. |
i solve this issue by adding edit SessionProvider and add baseUrl and basePath (baseURL + '/api/auth') to get baseUrl you can use this code
|
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
Your question
How to dynamically work with Passwordless/Email auth, without setting NEXTAUTH_URL.
What are you trying to do
I am working on a use-case where NEXTAUTH_URL is not fixed at deploy-time or build-time, but run-time, for a multi-domain (single codebase) scenario. This is to have Email passwordless only.
I have had good success with next-auth other providers for usual scenarios, and absolutely love the simplicity.
Feedback
I tried to browse around the code to get a sense of dependency of the deploy-time NEXTAUTH_URL, and it seems that it is use only to define the Url for
sendVerificationRequest
. If there was a way to pass it as an option, it would do it.Please advise, whats the best approach.
The text was updated successfully, but these errors were encountered: