nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
22.7k stars 3.03k forks source link

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

Closed robalmeister closed 2 months ago

robalmeister commented 3 months ago

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

semiautomatix commented 3 months ago

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 };
}
robalmeister commented 3 months ago

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 commented 3 months ago

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".

robalmeister commented 3 months ago

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 commented 3 months ago

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

tomcauf commented 3 months ago

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

Peace

ChrisB1123 commented 3 months ago

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 commented 3 months ago

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: https://github.com/nextauthjs/next-auth/blob/c0eb55806d28387ef2df6ba7648c229027a1cac3/packages/next-auth/src/lib/actions.ts#L118

tomcauf commented 3 months ago

@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

=> Deployment on vercel

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 commented 3 months ago

@tomcauf Could the error you see be this https://github.com/nextauthjs/next-auth/issues/9922 but in minified form?

prim1013 commented 3 months ago

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 commented 3 months ago

@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

robalmeister commented 3 months ago

Thanks it's working.

sooxt98 commented 3 months ago

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 commented 3 months ago

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 commented 3 months ago

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 commented 3 months ago

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

SebastianNarvaez11 commented 3 months ago

same problem innext-auth": "5.0.0-beta.13"

bestickley commented 3 months ago

Fix available here: https://github.com/nextauthjs/next-auth/pull/10094

robalmeister commented 3 months ago

@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 commented 3 months ago

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 commented 3 months ago

@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 commented 3 months ago

@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 commented 3 months ago

@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 next-auth@5.0.0-beta.13 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 commented 3 months ago

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? :pray:

mmmoli commented 3 months ago

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 commented 3 months ago

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

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 commented 3 months ago

@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 commented 3 months ago

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 commented 3 months ago

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 commented 2 months ago

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 ? https://github.com/nextauthjs/next-auth/issues/10224

ndom91 commented 2 months ago

@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 commented 2 months ago

@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 commented 2 months ago

@ndom91 Fixed it!!! Sorry for bothering you, turns out it was linked to https://github.com/nextauthjs/next-auth/issues/9922 and updating all dependencies worked

ndom91 commented 2 months ago

@DuarteMartinho ah okay great 🥳

Reqima-dev commented 2 months ago

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 commented 1 month ago

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",