-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
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
Authjs v5 redirecting to the wrong URL #10928
Comments
I'm working with subdomains and it seems with v5 I am getting redirected to localhost:3000 for a lot of things as opposed to the subdomain I am initiating from. v4 is not doing this. |
For me I needed to set the |
Yeah, same here. It works but we are using multi tenant, so it makes no sense since we don't know the HOST at build time, only runtime. Been trying to hack something together now for a couple of days, would love to use v5 but the redirections are just a no-go right now. |
For me with docker it's redirecting to the internal docker url, for example: One idea I had on how to fix this is that when providing the full callback url (with base url), it should not use the request url and instead use the full callback url provided. In this way it would be possible to for example just run the following code: await signIn(provider, {
...options,
redirect: false,
callbackUrl: new URL(callbackUrl, window.location.href).href,
}) Which would then be used to automatically get the correct callback url. In theory this can just be provided from the user and checked in the |
I'm having a similar issue. On mine, I have multiple subdomains with corresponding OAuth applications setup on both Google and Microsoft. The domains I'm using are I believe it's taking the root domain I have added |
Similar problem with local development, I have two apps on |
Few things to mention here.
Let me know if that helps any of you 🙏 If not, like I said, please check yuo're on the latest version and provide some more details please |
|
I think the main issue here is that in
It's using the |
Thanks for the quick response all!
Hmm yeah that seems like it might be a bug, it should also take into account, for example, the I'll take a look at the aforementioned repro above 🤔 |
Yeah, for mine it seems to be checking |
So I'm doing some digging through the code and I've found the following relevant parts: Regarding the
// From packages/core/src/lib/utils/env.ts:71
// Pseudocode:
const detectedHost = headers.get("x-forwarded-host") ?? headers.get("host")
const detectedProtocol =
headers.get("x-forwarded-proto") ?? protocol ?? "https"
const _protocol = detectedProtocol.endsWith(":")
? detectedProtocol
: detectedProtocol + ":"
url = new URL(`${_protocol}//${detectedHost}`)
return new URL(`${url}/${action}`)
Then, after that base action URL is generated, we get to the part where it appends the // From packages/next-auth/src/lib/actions.ts:25
// Pseudocode:
const callbackUrl = redirectTo?.toString() ?? headers.get("Referer") ?? "/"
const signInURL = createActionURL(...)
signInURL.searchParams.append("callbackUrl", callbackUrl)
return signInURL.toString() So long story short, without Regarding the |
Hey @ndom91, attached a video just to make sure we are on the same page. No |
@kevinmitch14 thanks for the quick video! Can you share that repo? Looks like a nice minimal reproduction.. But yeah, so it looks like the callbackUrl that i mentioned in the second code snippet, that gets appended onto an action URL, like So it looks to me like the critical piece(s) of code are at This takes two different paths, dpending on whether Btw, sidenote, but since v5 only the |
@ndom91 its the same one in the issue #10915. https://github.com/kevinmitch14/next-auth-subdomains
Thanks, I've been changing between v4/v5 so just have both. But in reality I don't have any set, because I don't know it at build time. It depends on the subdomain being used. |
Basically, that We can see from the code that in the case of not having an Ex: export function createActionURL(
action: AuthAction,
protocol: string,
headers: Headers,
envObject: any,
basePath?: string
): URL {
let envUrl = envObject.AUTH_URL ?? envObject.NEXTAUTH_URL
let url: URL
if (envUrl) {
url = new URL(envUrl)
if (basePath && basePath !== "/" && url.pathname !== "/") {
logger.warn(
url.pathname === basePath
? "env-url-basepath-redundant"
: "env-url-basepath-mismatch"
)
url.pathname = "/"
}
} else {
const detectedHost = headers.get("x-forwarded-host") ?? headers.get("host")
const detectedProtocol =
headers.get("x-forwarded-proto") ?? protocol ?? "https"
const _protocol = detectedProtocol.endsWith(":")
? detectedProtocol
: detectedProtocol + ":"
url = new URL(`${_protocol}//${detectedHost}`)
} |
@kevinmitch14 so I cloned your repro and was abel to reproduce the same issue as you. It seems that the issue comes from the For the case of the |
Interesting, I never noticed that. 🤔 For reference, the same flow works in v4 as normal. I think there's a v4 setup in my repo that is commented out. I do think I was having the similar issues when using the |
Are you using Next.js middleware in when using v4? Everythign else is the same? It looks like the For example, my random domain that I also added some logging to the "root" http handler's that we export from I'm a bit at a loss for where to look next haha |
Yeah Also for me, it actually redirects to https://localhost:3000 if I'm on a https secured domain, so there's likely something going on with the URL getting modifed. |
I forgot to add the original error, but this is the error logged to the console when this redirect happens:
Setting |
I do face this weird issue. After being logged in, I could see the cookie I use |
I'm having the same issue. I have set to AUTH_TRUST_HOST=true. |
Fixed my issue by using those two environment variables.
This should work for now, until the issue is fixed. |
Yeah a workaround for avoiding the auto-parsing of the origin, etc. is to set it manually with |
yeah lol but that means i can't use multiple domains haha |
Yeah I know its not a fix, just wanted to confirm as a sort of work around. Back on topic.. I'm honestly not sure what we can do if Next.js isn't reporting the right host. Someone mentioned that the Any other ideas? |
For some reason on v4, it redirects to the correct place so it seems like something in v5 is causing this? For me atleast, I'm not sure about @IncognitoTGT's use-case as it could be a bit different. |
My use case is just multiple domains for a oauth provider that supports multple callbacks |
The same issue happens in Docker I made a repo so it's easier to reproduce if ya'll want to take a stab at debugging it in docker: #8449 (comment) Thanks. |
I am experiencing the same issue with next-auth when using Next.js (version 14.2.3) and next-auth (^5.0.0-beta.18). My setup involves running Next.js inside a Docker container, behind Traefik as a reverse proxy. Traefik is configured to forward the Problem Details: 1. Default Callback URL: When I do not set the 2. Callback URL Override: Passing a 3. Setting the AUTH_URL results in an SSL SELF_SIGNED_CERT_IN_CHAIN error.
Weirdly, it works when I start Next.js in development mode and subsequently set the Expected Behavior: |
I've found a workaround that works well for me. My setup
My environment variables: AUTH_TRUST_HOST=true
AUTH_REDIRECT_PROXY_URL=https://stable.dev.domain.com/api/auth
AUTH_SECRET=mysecret The workaround code: // In src/app/api/[...nextauth]/route.ts
import { handlers } from "@/auth"
import { NextRequest } from "next/server"
const reqWithTrustedOrigin = (req: NextRequest): NextRequest => {
if (process.env.AUTH_TRUST_HOST !== 'true') return req
const proto = req.headers.get('x-forwarded-proto')
const host = req.headers.get('x-forwarded-host')
if (!proto || !host) {
console.warn("Missing x-forwarded-proto or x-forwarded-host headers.")
return req
}
const envOrigin = `${proto}://${host}`
const { href, origin } = req.nextUrl
return new NextRequest(href.replace(origin, envOrigin), req)
}
export const GET = (req: NextRequest) => {
return handlers.GET(reqWithTrustedOrigin(req))
}
export const POST = (req: NextRequest) => {
return handlers.POST(reqWithTrustedOrigin(req))
} This is based on https://github.com/nextauthjs/next-auth/blob/next-auth%405.0.0-beta.19/packages/next-auth/src/lib/env.ts#L6 where AUTH_URL is used to set the request origin. You would think setting AUTH_TRUST_HOST would do this automatically, but I guess it doesn't? |
This works for me! Finally, I was about to give up. |
Thank you for this. This works perfectly for me :) |
Using What do you think? |
I myself used the workaround listed here and that solved that issue |
I'm getting this error and I think it's caused because it's fetching the callback URL at build-time instead of runtime:
Any chance we can use this? https://www.npmjs.com/package/next-runtime-env |
Hey together, I have the same issue at Next.JS 15.1.3 and the workaround does not help.
Some Ideas? |
reopening since this issue seems to not actually be fixed |
Thanks @IncognitoTGT FYI: I'm trying to host on azure web app. |
I'm having this problem also, for me the problem is that I'm running a separate node express backend, from a frontend in nextjs. The backend runs on port 4000, and frontend in port 3000 in localhost. I do forward al localhost:3000/api requests to localhost:4000/api, and auth.js runs in the backend, so I would expect to call google callback with localhost:3000/api/auth/callback/google, but it uses por 4000 instead. How do you deal with this? Is it mandatory to use backend and frontend in the same service with Auth.js then? It seems to completely ignore the AUTH_URL env |
Ok, forcing the AUTH_REDIRECT_PROXY_URL=http://localhost:3000/api/auth did the trick for me. So AUTH_URL is always the frontend url domain without anything more? AUTH_URL=http://localhost:3000 ? |
Environment
Reproduction URL
https://github.com/spaceness/stardust/fixed, and project has a rewrite not using auth.js
Describe the issue
When I use Auth.js with an OAuth provider, like in my case Auth0, it redirects to localhost:3000 even if I'm logging in through a VSCode devtunnels or Tailscale funnel. In fact, this issue actually happens on every other URL.
There is an error with the server expecting the tunnel's URL but getting localhost.
How to reproduce
Setup the repository (only the nextauth and the DB stuff), and then try to login with a non localhost URL.
Expected behavior
It should redirect from the initial URL where the attempt was initiated from.
The text was updated successfully, but these errors were encountered: