Skip to content
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

Autodetect protocol+host behind proxy without AUTH_URL env variable #10081

Closed
deestt opened this issue Feb 20, 2024 · 39 comments · Fixed by #10094
Closed

Autodetect protocol+host behind proxy without AUTH_URL env variable #10081

deestt opened this issue Feb 20, 2024 · 39 comments · Fixed by #10094
Labels
enhancement New feature or request

Comments

@deestt
Copy link

deestt commented Feb 20, 2024

Environment

System:
OS: Windows 11 10.0.22631
CPU: (12) x64 AMD Ryzen 5 2600 Six-Core Processor
Memory: 1.05 GB / 15.91 GB
Binaries:
Node: 18.17.0 - C:\Program Files\nodejs\node.EXE
Yarn: 4.1.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 10.4.0 - C:\Program Files\nodejs\npm.CMD
pnpm: 8.6.1 - ~\AppData\Local\pnpm\pnpm.EXE
Browsers:
Edge: Chromium (121.0.2277.128)
Internet Explorer: 11.0.22621.1
npmPackages:
@auth/core: latest => 0.27.0
@auth/prisma-adapter: ^1.4.0 => 1.4.0
next: latest => 14.1.0
next-auth: 5.0.0-beta.11 => 5.0.0-beta.11
react: ^18.2.0 => 18.2.0

Reproduction URL

https://github.com/robalmeister/next-auth-example/

Describe the issue

[auth][error] UnknownAction: Cannot parse action at /session .Read more at https://errors.authjs.dev#unknownaction
    at parseActionAndProviderId (webpack-internal:///(middleware)/./node_modules/@auth/core/lib/utils/web.js:87:27)
    at toInternalRequest (webpack-internal:///(middleware)/./node_modules/@auth/core/lib/utils/web.js:32:40)
    at Auth (webpack-internal:///(middleware)/./node_modules/@auth/core/index.js:82:103)
    at getSession (webpack-internal:///(middleware)/./node_modules/next-auth/lib/index.js:22:60)
    at handleAuth (webpack-internal:///(middleware)/./node_modules/next-auth/lib/index.js:135:35)
    at Object.eval [as handler] (webpack-internal:///(middleware)/./node_modules/next-auth/lib/index.js:105:20)
    at eval (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/adapter.js:193:27)
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at Object.wrap (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/async-storage/request-async-storage-wrapper.js:81:24)
    at eval (webpack-internal:///(middleware)/./node_modules/next/dist/esm/server/web/adapter.js:180:122)
{ x-middleware-next: '1' }
{ x-middleware-next: '1' }

How to reproduce

try to signin

Expected behavior

signin page

@deestt deestt added bug Something isn't working triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. labels Feb 20, 2024
@semiautomatix
Copy link

Something to do with the basePath:

const { action, providerId } = parseActionAndProviderId(url.pathname, config.basePath);

// url.pathname '/api/auth/session'
// config.basePath '/auth'

export function parseActionAndProviderId(pathname, base) {
    const a = pathname.match(new RegExp(`^${base}(.+)`));
    if (a === null)
        throw new UnknownAction(`Cannot parse action at ${pathname}`);
    const [_, actionAndProviderId] = a;
    const b = actionAndProviderId.replace(/^\//, "").split("/");
    if (b.length !== 1 && b.length !== 2)
        throw new UnknownAction(`Cannot parse action at ${pathname}`);
    const [action, providerId] = b;
    if (!isAuthAction(action))
        throw new UnknownAction(`Cannot parse action at ${pathname}`);
    if (providerId && !["signin", "callback", "webauthn-options"].includes(action))
        throw new UnknownAction(`Cannot parse action at ${pathname}`);
    return { action, providerId };
}

@deestt
Copy link
Author

deestt commented Feb 20, 2024

I add in config basePath: "/' and I have new error:

[auth][error] UnknownAction: Cannot parse action at /api/auth/session .Read more at https://errors.authjs.dev#unknownaction
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:1:45202
    at tL (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:1:45400)
    at i$ (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:357:46233)
    at t (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:357:57799)
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:367:84433
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:367:98628
    at i.with (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:13179)
    at l.with (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:7379)
    at l.startActiveSpan (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:22431)
    at i.startActiveSpan (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:22965)

@semiautomatix
Copy link

I add in config basePath: "/' and I have new error:

[auth][error] UnknownAction: Cannot parse action at /api/auth/session .Read more at https://errors.authjs.dev#unknownaction
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:1:45202
    at tL (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:1:45400)
    at i$ (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:357:46233)
    at t (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:357:57799)
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:367:84433
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:367:98628
    at i.with (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:13179)
    at l.with (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:7379)
    at l.startActiveSpan (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:22431)
    at i.startActiveSpan (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\app\api\auth\[...nextauth]\route.js:362:22965)

Try setting the base path to "/api/auth".

@deestt
Copy link
Author

deestt commented Feb 20, 2024

I got a error

[auth][error] UnknownAction: Cannot parse action at /session .Read more at https://errors.authjs.dev#unknownaction
    at parseActionAndProviderId (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:7491:27)
    at toInternalRequest (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:7436:40)
    at Auth (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:13860:35)
    at getSession (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:14563:12)
    at handleAuth (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:14675:35)
    at Object.handler (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:14646:20)
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:2386:27
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at Object.wrap (C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:1909:24)
    at C:\Users\Filip\Documents\GitHub\next-auth-example\.next\server\middleware.js:2373:47

@pjborowiecki
Copy link

Had the same problem yesterday and it disappeared after removing NEXTAUTH_URL from my environment variables

@tomcauf
Copy link

tomcauf commented Feb 21, 2024

Hey ! I had the same problem, and it resolves after removing NEXTAUTH_URL or AUTH_URL from environment variables.

Peace

@ChrisB1123
Copy link

If I delete the AUTH_URL from my environment variables, then I end up getting redirected to localhost in production?

I saw on a stack overflow question to add api/auth to the end of the AUTH_URL, but then I end up with this weird bug

2024-02-21T08:05:10.659708+00:00 app[web.1]:  ⨯ TypeError: iz is not a constructor
2024-02-21T08:05:10.659754+00:00 app[web.1]:     at iB (/app/.next/server/chunks/973.js:373:50463)
2024-02-21T08:05:10.659755+00:00 app[web.1]:     at t (/app/.next/server/chunks/973.js:373:56275)
2024-02-21T08:05:10.659755+00:00 app[web.1]:     at /app/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:42490
2024-02-21T08:05:10.659756+00:00 app[web.1]:     at /app/node_modules/next/dist/server/lib/trace/tracer.js:133:36
2024-02-21T08:05:10.659756+00:00 app[web.1]:     at NoopContextManager.with (/app/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7062)
2024-02-21T08:05:10.659757+00:00 app[web.1]:     at ContextAPI.with (/app/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:518)
2024-02-21T08:05:10.659757+00:00 app[web.1]:     at NoopTracer.startActiveSpan (/app/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18093)
2024-02-21T08:05:10.659758+00:00 app[web.1]:     at ProxyTracer.startActiveSpan (/app/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18854)
2024-02-21T08:05:10.659758+00:00 app[web.1]:     at /app/node_modules/next/dist/server/lib/trace/tracer.js:122:103
2024-02-21T08:05:10.659758+00:00 app[web.1]:     at NoopContextManager.with (/app/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7062)

@bwallberg
Copy link
Contributor

bwallberg commented Feb 21, 2024

I faced the same issue and managed to workaround the issue by setting AUTH_URL to http://localhost:3000/api/auth.

The cause seems to be that basePath is unused here:

export function createActionURL(

@tomcauf
Copy link

tomcauf commented Feb 21, 2024

@ChrisB1123 @bwallberg
This is the same error as NEXTAUTH_URL, just in a different form.
I see I'm not the only one with this problem x).

I tried to deploy in 2 different ways :
=> Deployment on my debian server

  • Here, I got the same error as you, all redirects point to localhost and not my domain name. When I set AUTH_URL, no redirection issue, but the error TypeError: iz is not a constructor. So it's impossible to run this version on my server

=> Deployment on vercel

  • Here, I had no issues, I don't know what vercel does as a config or what, but all redirections worked correctly. It's quite strange..

For those who will tell me that my server is badly configured, no, because with NextAuth 4, I don't have any problems. (but maybe my bad if that's the case)

Unfortunately, after a few hours of research yesterday, I couldn't find a solution...

Perhaps @ThangHuuVu might have a solution for us ?

@bwallberg
Copy link
Contributor

@tomcauf Could the error you see be this #9922 but in minified form?

@prim1013
Copy link

I get the same "not a constructor" error in my azure deployment environment (works fine locally).

It's coming from reqWithEnvURL

However, If I remove NEXTAUTH_URL/AUTH_URL then the callbackUrl that it uses when I am redirected to the signin page is localhost:8080 instead of the domain of my deployment i.e. aspen-auth-example.azurewebsites.net

This is the incorrect callbackUrl
https://aspen-auth-example.azurewebsites.net/api/auth/signin?callbackUrl=https%3A%2F%2Flocalhost%3A8080%2F

@ChrisB1123
Copy link

ChrisB1123 commented Feb 21, 2024

@prim1013 @tomcauf

I made a separate issue: #10092

My temporary fix has been to revert to next-auth v5.0.0-beta.4, which also required pegging to @auth/core v0.18.4 and @auth/prisma-adapter v1.0.9 to avoid typescript errors

@deestt
Copy link
Author

deestt commented Feb 21, 2024

Thanks it's working.

@deestt deestt closed this as completed Feb 21, 2024
@sooxt98
Copy link
Contributor

sooxt98 commented Feb 21, 2024

i can confirm setting custom basePath in auth.config.js could trigger this issue,
im currently removed it until this fixes

this issue doesn't relate to any package version issue, neither upstream nor itself

@lapa182
Copy link

lapa182 commented Feb 21, 2024

I get the same "not a constructor" error in my azure deployment environment (works fine locally).

It's coming from reqWithEnvURL

However, If I remove NEXTAUTH_URL/AUTH_URL then the callbackUrl that it uses when I am redirected to the signin page is localhost:8080 instead of the domain of my deployment i.e. aspen-auth-example.azurewebsites.net

This is the incorrect callbackUrl https://aspen-auth-example.azurewebsites.net/api/auth/signin?callbackUrl=https%3A%2F%2Flocalhost%3A8080%2F

Did you manage to fix this issue? I'm having the same one. Locally without AUTH_URL/NEXTAUTH_URL works fine, but without it it's trying to redirect to the docker_name:8080.

@prim1013
Copy link

I get the same "not a constructor" error in my azure deployment environment (works fine locally).
It's coming from reqWithEnvURL
However, If I remove NEXTAUTH_URL/AUTH_URL then the callbackUrl that it uses when I am redirected to the signin page is localhost:8080 instead of the domain of my deployment i.e. aspen-auth-example.azurewebsites.net
This is the incorrect callbackUrl https://aspen-auth-example.azurewebsites.net/api/auth/signin?callbackUrl=https%3A%2F%2Flocalhost%3A8080%2F

Did you manage to fix this issue? I'm having the same one. Locally without AUTH_URL/NEXTAUTH_URL works fine, but without it it's trying to redirect to the docker_name:8080.

No fix - I just reverted back to v5.0.0-beta.4 as mentioned above. Unfortunately that broke my CredentialsProvider but once #10092 is fixed we should be able to hop back on latest version and be good.

@bestickley
Copy link

@robalmeister, why was this closed? I'm still experiencing on next-auth": "5.0.0-beta.13"

@SebastianNarvaez11

This comment was marked as off-topic.

@bestickley
Copy link

Fix available here: #10094

@deestt
Copy link
Author

deestt commented Feb 22, 2024

@robalmeister, why was this closed? I'm still experiencing on next-auth": "5.0.0-beta.13"

because when I remove AUTH_URL it's working

@balazsorban44 balazsorban44 reopened this Feb 23, 2024
@balazsorban44
Copy link
Member

balazsorban44 commented Feb 23, 2024

Hi all, quick check-in. NEXTAUTH_URL or AUTH_URL are rarely needed nowadays, as we try to infer the protocol/host from the incoming request headers (hence the trustHost: true requirement if you self-host). You haven't needed these env variables for maybe years, even in v4.

We would like to keep things working as before though, so I appreciate the dig-deep in this issue. We will look at the PR. I honestly thought I fixed this via #9955

Explanation: It's technically always been required to have the base path defined as part of the env variable URL (NEXTAUTH_URL or AUTH_URL), but it worked without it before. So we should strive to keep supporting it. But it would be more correct if:

  1. you added /api/auth (or the path up until your [...nextauth].ts file.) to the env variable
  2. dropped the env variable and set basePath if the default /api/auth is not working for you

@prim1013
Copy link

@balazsorban44 thank you for the update and for all your contributions.

Some additional info: I have removed the env variable and have trustHost: true and basePath: "/api/auth" in my config and when I try to access a protected route I get localhost in the callbackUrl - https://aspen-auth-example.azurewebsites.net/auth/signin?callbackUrl=https%3A%2F%2Flocalhost%3A8080%2F

I am running

"next": "^14.1.1-canary.70",
"next-auth": "^5.0.0-beta.13",

@oscarmylla
Copy link

@balazsorban44 Is there an alternative solution to setting the AUTH_URL if you are using a subdomain (http://app.localhost:3000)? When the env is not included, the authjs.callback-url cookie is set to http://localhost:3000 even if the sign in comes from the subdomain.

@bestickley
Copy link

bestickley commented Feb 23, 2024

@balazsorban44, thank you for your attention to this issue :)

NEXTAUTH_URL or AUTH_URL are rarely needed nowadays, as we try to infer the protocol/host from the incoming request headers (hence the trustHost: true requirement if you self-host). You haven't needed these env variables for maybe years, even in v4.

I am using [email protected] in a Next.js app behind CloudFront + ALB + ECS Fargate. Based on my experience, the protocol/host is not inferred from the request headers. The CloudFront domain (i.e. d3l665bfs8sngd.cloudfront.net) is the "Host" header but the "callbackUrl" generated from next-auth is http://ip-10-0-65-125.ec2.internal (without AUTH_URL) which is tied to the local network (printed by Next.js on start up that looks like "- Local: http://ip-10-0-65-125.ec2.internal:3000").

Hopefully that demonstrates the need for AUTH_URL isn't necessarily "rare". Again, thank you for your time looking into this!

@balazsorban44
Copy link
Member

balazsorban44 commented Feb 23, 2024

It sounds like all your use cases are legit to use AUTH_URL then (which is hosting behind a proxy). From the looks of it, you would need:

@prim1013 - AUTH_URL="https://aspen-auth-example.azurewebsites.net/api/auth"

@oscarmylla - AUTH_URL="http://app.localhost:3000/api/auth" (assuming you have api/auth/[...nextauth])

@bestickley - AUTH_URL="https://d3l665bfs8sngd.cloudfront.net/api/auth" (assuming you have api/auth/[...nextauth])

Although, I think we could make these work without the env variable too, if we detect x-forwarded-proto+x-forwarded-host and fall back to host here instead: https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/lib/utils/web.ts/#L35

You would still need trustHost: true, as Auth.js cannot reliably know if your environment takes the necessary measures against host header attacks. (Vercel for example does, hence it doesn't require this setting.)

@bwallberg as such, I think #10094 won't be sufficient in its current form, as it only focuses on next-auth. Would you be interested in updating the PR as described above? 🙏

@mmmoli
Copy link

mmmoli commented Feb 23, 2024

It sounds like all your use cases are legit to use AUTH_URL then (which is hosting behind a proxy). From the looks of it, you would need:

@prim1013 - AUTH_URL="https://aspen-auth-example.azurewebsites.net/api/auth"

@oscarmylla - AUTH_URL="http://app.localhost:3000/api/auth" (assuming you have api/auth/[...nextauth])

@bestickley - AUTH_URL="https://d3l665bfs8sngd.cloudfront.net/api/auth" (assuming you have api/auth/[...nextauth])

Although, I think we could make these work without the env variable too, if we detect x-forwarded-proto+x-forwarded-host and fall back to host here instead: https://github.com/nextauthjs/next-auth/blob/main/packages/core/src/lib/utils/web.ts/#L35

You would still need trustHost. true, as Auth.js cannot reliably know if your environment takes the necessary measures against host header attacks. (Vercel for example does, hence it doesn't require this setting.)

@bwallberg as such, I think #10094 won't be sufficient in its current form, as it only focuses on next-auth. Would you be interested in updating the PR as described above? 🙏

Fkn awesome response: Helpful & Robust. I'm not even involved but you deserve applause. Thanks @balazsorban44 👏🏻 🎉

@balazsorban44 balazsorban44 added enhancement New feature or request and removed triage Unseen or unconfirmed by a maintainer yet. Provide extra information in the meantime. bug Something isn't working labels Feb 23, 2024
@balazsorban44 balazsorban44 changed the title UnknownAction: Cannot parse action at /session Autodetect protocol+host behind proxy without AUTH_URL env variable Feb 23, 2024
@balazsorban44
Copy link
Member

If this is implemented, it might essentially kill the need for AUTH_URL in any scenario. 🤔

You would only need to tweak basePath and only if your [...nextauth]/route.ts file is not under the app/api/auth path (which is totally legit, App Router doesn't enforce you under /api!)

@bwallberg
Copy link
Contributor

bwallberg commented Feb 26, 2024

@balazsorban44

I wouldn't mind investigating using x-forwarded-xyz, I will try to setup an environment where I can reproduce said headers. While I do believe most environments would allow those headers to be passed along I wouldn't trust it so AUTH_URL will probably "have to" be supported indefinitely.

I don't understand why the PR I created would be insufficient though? My PR solves the specific issue related to "cannot parse action at /session" for specifically next-auth and should cover all the different variations of provided AUTH_URL for that issue.

However if the intention is that you must suffix the env variable with /api/auth ( in next-auth v4 you only needed to supply the basePath if you used a custom one, but right now I have to suffix it even though I don't have a custom one ) then I will simply close my PR.

@tannerhladek
Copy link

tannerhladek commented Feb 27, 2024

late to this party, but where exactly did this land? I am encountering the same issue where my production environment callback is directing to http://localhost:3010 versus the correct proxy domain.

I tried setting AUTH_URL to the correct non-localhost value and setting trustHost: true, but that does not appear to be working.

I am using the below:

"next": "v14.1.1-canary.76",
"next-auth": "^5.0.0-beta.13",

UPDATE:
setting the env variable AUTH_URL=http://{domain}:3010/api/auth and using the below versions of next and next-auth seem to fix the issue.

"next": "v14.1.1-canary.76",
"next-auth": "^5.0.0-beta.4",

I will continue to track this.

@ndom91
Copy link
Member

ndom91 commented Feb 28, 2024

Note to anyone else coming across this issue:

Currently (5.0.0-beta.13), if using a proxy, you have to set the AUTH_URL to the full path to your /auth route, i.e. AUTH_URL=http://localhost:3000/api/auth, and set trustHost: true in your config.

We're investigating detecting the proxy host and path as well so you can completely drop AUTH_URL potentially.

@DuarteMartinho
Copy link

DuarteMartinho commented Mar 5, 2024

Sorry if it unrelated to this post but i'm getting the errors on this post

here is my copy of the errors:

[auth][error] UnknownAction: Cannot parse action at /session .Read more at https://errors.authjs.dev#unknownaction
    at parseActionAndProviderId (/usr/src/app/codepair/.next/server/middleware.js:7703:27)
    at toInternalRequest (/usr/src/app/codepair/.next/server/middleware.js:7647:40)
    at Auth (/usr/src/app/codepair/.next/server/middleware.js:14033:35)
    at getSession (/usr/src/app/codepair/.next/server/middleware.js:14737:12)
    at handleAuth (/usr/src/app/codepair/.next/server/middleware.js:14851:35)
    at Object.request [as handler] (/usr/src/app/codepair/.next/server/middleware.js:14832:24)
    at /usr/src/app/codepair/.next/server/middleware.js:2391:27
    at AsyncLocalStorage.run (node:async_hooks:346:14)
    at Object.wrap (/usr/src/app/codepair/.next/server/middleware.js:1914:24)
    at /usr/src/app/codepair/.next/server/middleware.js:2378:47
 ⨯ TypeError: iz is not a constructor
    at iG (/usr/src/app/codepair/.next/server/chunks/678.js:373:50439)
    at t (/usr/src/app/codepair/.next/server/chunks/678.js:373:56341)
    at /usr/src/app/codepair/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:42490
    at /usr/src/app/codepair/node_modules/next/dist/server/lib/trace/tracer.js:133:36
    at NoopContextManager.with (/usr/src/app/codepair/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7062)
    at ContextAPI.with (/usr/src/app/codepair/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:518)
    at NoopTracer.startActiveSpan (/usr/src/app/codepair/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18093)
    at ProxyTracer.startActiveSpan (/usr/src/app/codepair/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:18854)
    at /usr/src/app/codepair/node_modules/next/dist/server/lib/trace/tracer.js:122:103
    at NoopContextManager.with (/usr/src/app/codepair/node_modules/next/dist/compiled/@opentelemetry/api/index.js:1:7062)

Followed the steps provided
Setted trustHost: true in auth config
Setted AUTH_URL to the URL on the proxy i.e frontend.mydomain.com (also tried frontend.mydomain.com/api/auth and both give same result)
after that going to frontend.mydomain.com/api/auth/providers
i now get the following a status 500 and the erros above
@ndom91 Do you think you can reopen this ticket to provide more info ? #10224

@ndom91
Copy link
Member

ndom91 commented Mar 6, 2024

@DuarteMartinho unfortunately we can't reopen it, it's locked.

But anyway, have you set the AUTH_SECRET env var too? Make sure you set that and then try the AUYH_URL with path.

Make sure youve read and follow all the setup instructions - https://authjs.dev/reference/nextjs#installation

@DuarteMartinho
Copy link

@ndom91

So yeah i can confirm that all the variable are set
AUTH_URL
AUTH_SECRET
GITHUB_CLIENT_ID
GITHUB_CLIENT_SECRET

For more context here is my auth.js

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

import { db } from '@/lib/db';

import { getUserById } from '@/lib/user-service';
import { getAccountByUserId } from '@/lib/accounts-service';

export const {
  handlers: { GET, POST },
  auth,
  signOut,
} = NextAuth({
  callbacks: {
    async jwt({ token }) {
      if (!token.sub) return token;

      const existingUser = await getUserById(token.sub);

      if (!existingUser) return token;

      const existingAccount = await getAccountByUserId(existingUser.id);

      token.isOAuth = !!existingAccount;
      token.name = existingUser.name;
      token.email = existingUser.email;
      token.role = existingUser.role;
      return token;
    },
  },
  pages: {
    signIn: '/auth/login',
    error: '/auth/error',
  },
  adapter: PrismaAdapter(db),
  session: { strategy: 'jwt' },
  trustHost: true,
  providers: [
    GitHub({
      authorization: {
        params: {
          scope: 'user:email repo',
        },
      },
      clientId: process.env.GITHUB_CLIENT_ID,
      clientSecret: process.env.GITHUB_CLIENT_SECRET,
    }),
  ],
});

And app/api/auth/[...nextauth]/route.ts

export { GET, POST } from '@/auth';

Can't turn on edge because of db

also package.json

"dependencies": {
    "@auth/prisma-adapter": "^1.5.0",
    "@prisma/client": "^5.10.2",
    "next": "14.1.0",
    "next-auth": "^5.0.0-beta.15",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
  },

In localhost everything works fine, the problem is when i set the ENV AUTH_URL that breaks everything

let me know if you need anything else that could try help debug

@DuarteMartinho
Copy link

@ndom91 Fixed it!!! Sorry for bothering you, turns out it was linked to #9922 and updating all dependencies worked

@ndom91
Copy link
Member

ndom91 commented Mar 6, 2024

@DuarteMartinho ah okay great 🥳

@Reqima-dev
Copy link

Salut à tous, enregistrement rapide. NEXTAUTH_URLou AUTH_URLsont rarement nécessaires de nos jours, car nous essayons de déduire le protocole/l'hôte à partir des en-têtes de requêtes entrantes (d'où l' trustHost: trueexigence si vous vous auto-hébergez). Vous n'avez pas eu besoin de ces variables d'environnement depuis peut-être des années, même dans la v4.

Nous aimerions cependant que les choses continuent de fonctionner comme avant, c'est pourquoi j'apprécie d'approfondir ce problème. Nous examinerons le PR. Honnêtement, je pensais avoir résolu ce problème via #9955

Explication : Techniquement, il a toujours été nécessaire que le chemin de base soit défini dans le cadre de l'URL de la variable d'environnement ( NEXTAUTH_URLou AUTH_URL), mais cela fonctionnait sans cela auparavant. Nous devrions donc nous efforcer de continuer à le soutenir. Mais il serait plus correct si :

  1. vous avez ajouté /api/auth(ou le chemin jusqu'à votre [...nextauth].tsfichier.) à la variable env
  2. supprimé la variable env et défini basePathsi la valeur par défaut /api/authne fonctionne pas pour vous

Pour moi à marcher correctement. Merci beaucoup

@vatoer
Copy link

vatoer commented Apr 19, 2024

so what's the final solution for the production behind proxy,

in production

https://{domain}/api/auth/providers

problem 1
without AUTH_URL it always redirect to localhost

{"credentials":{"id":"credentials","name":"Credentials","type":"credentials","signinUrl":"http://localhost:3000/api/auth/signin/credentials","callbackUrl":"http://localhost:3000/api/auth/callback/credentials"}}

problem 2
and when I set AUTH_URL=https://{domain}/api/auth

I got error

iz is not a constructor

version

    "next-auth": "5.0.0-beta.13",

also

    "next-auth": "5.0.0-beta.15",

@kosz
Copy link

kosz commented Aug 1, 2024

still getting this issue with beta.20

it just started ocuring out of the blue had it working before, but the working code not working anymore.

removing auth_url will direct to localhost in production

@richard-thai
Copy link

richard-thai commented Oct 31, 2024

We encountered a similar issue and here’s how we resolved it.

`
import NextAuth, { NextAuthResult } from 'next-auth';
import { NextRequest } from 'next/server';
import 'server-only';
import { entraAuthConfig } from './entra-auth-config';

const nextAuthResult = NextAuth(entraAuthConfig);

const DEFAULT_AUTH_API_PATH = '/api/auth';

// A work around for the inferred type error TS2742
export const auth: NextAuthResult['auth'] = nextAuthResult.auth;
const { GET, POST }: NextAuthResult['handlers'] = nextAuthResult.handlers;

const proxyHandler = (handler: (req: NextRequest) => Promise) => {
return async (req: NextRequest): Promise => {
if (entraAuthConfig.basePath && !new RegExp(
^${entraAuthConfig.basePath}(.+)).test(req.nextUrl.pathname)) {

        const url = new URL(
            req.nextUrl.pathname.replace(DEFAULT_AUTH_API_PATH, entraAuthConfig.basePath),
            req.nextUrl.origin,
        );
        url.search= req.nextUrl.search;
        
        req.nextUrl.href=url.href;
        req.nextUrl.pathname=url.pathname;

        return handler(
            new Proxy(req, {
                get(target, prop, receiver) {
                    switch (prop) {
                        case 'url':
                            return url.href;
                        
                        default:
                            return Reflect.get(target, prop, receiver);
                    }
                },
            }),
        );
    }
    return handler(req);
};

};

export const handlers = { GET: proxyHandler(GET), POST: proxyHandler(POST) } as const;

export const { signIn, signOut } = nextAuthResult;
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.