next-auth icon indicating copy to clipboard operation
next-auth copied to clipboard

@auth/core@{0.22.0 / 0.23.0 / 0.24.0} breaking custom OAuth provider

Open digoburigo opened this issue 5 months ago • 8 comments

Provider type

Custom provider

Environment

Dependecies: "next": "^14.0.4" "react": "18.2.0" "next-auth": "5.0.0-beta.5" "@auth/core": "0.23.0" System: OS: macOS 14.3 CPU: (8) arm64 Apple M1 Pro Memory: 76.13 MB / 16.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 20.11.0 - ~/.nvm/versions/node/v20.11.0/bin/node npm: 10.2.4 - ~/.nvm/versions/node/v20.11.0/bin/npm pnpm: 8.14.3 - ~/.nvm/versions/node/v20.11.0/bin/pnpm bun: 1.0.25 - ~/.bun/bin/bun Browsers: Brave Browser: 120.1.61.120 Chrome: 121.0.6167.85 Safari: 17.3

Reproduction URL

https://github.com/digoburigo/nextjs-auth-custom-oauth

Describe the issue

I have this strategy in my NextAuth config

providers: [
    {
      id: "foo",
      name: "foo",
      type: "oidc",
      wellKnown: `http://localhost:3002/.well-known/openid-configuration/`,
      issuer: `http://localhost:3002`,
      userinfo: `http://localhost:3002/userinfo/`,
      jwks_endpoint: `http://localhost:3002/.well-known/jwks.json`,
      token: `http://localhost:3002/token/`,
      authorization: {
        url: `http://localhost:3002/authorize/`,
        params: { scope: "openid profile email" },
      },
      profile(profile, tokens) {
        console.log(`tokens:`, tokens);
        console.log(`profile:`, profile);
        return profile;
      },
      clientId: "foo",
      clientSecret: "bar",
    } satisfies OIDCConfig<Profile>,
  ],

There is no need to test if login is working because error happens before this flow anyways.

version 0.21.0 working properly: @acme/nextjs:dev: session: null

versions after 0.21.0 (0.22.0 / 0.23.0 / 0.24.0 at the moment) error occurs:

@acme/nextjs:dev: [auth][error] UnknownAction: Cannot parse action at //session .Read more at https://errors.authjs.dev#unknownaction
@acme/nextjs:dev:     at parseActionAndProviderId (webpack-internal:///(rsc)/../../node_modules/@auth/core/lib/utils/web.js:98:27)
@acme/nextjs:dev:     at toInternalRequest (webpack-internal:///(rsc)/../../node_modules/@auth/core/lib/utils/web.js:40:40)
@acme/nextjs:dev:     at Auth (webpack-internal:///(rsc)/../../node_modules/@auth/core/index.js:75:103)
@acme/nextjs:dev:     at getSession (webpack-internal:///(rsc)/../../node_modules/next-auth/lib/index.js:20:60)
@acme/nextjs:dev:     at eval (webpack-internal:///(rsc)/../../node_modules/next-auth/lib/index.js:94:20)
@acme/nextjs:dev:     at AuthShowcase (webpack-internal:///(rsc)/./src/app/_components/auth-showcase.tsx:18:75)
@acme/nextjs:dev:     at attemptResolveElement (webpack-internal:///(rsc)/../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.development.js:1451:30)
@acme/nextjs:dev:     at resolveModelToJSON (webpack-internal:///(rsc)/../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.development.js:1754:41)
@acme/nextjs:dev:     at Array.toJSON (webpack-internal:///(rsc)/../../node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.development.js:1293:28)
@acme/nextjs:dev:     at stringify (<anonymous>)
@acme/nextjs:dev: session: Error: This action with HTTP GET is not supported.

How to reproduce

There is the README.md on the github repo mentioned above on how to reproduce the error.

Expected behavior

I expect that the behavior is similar to 0.21.0 or if there is some undocumented breaking change that I need to know about.

digoburigo avatar Jan 26 '24 20:01 digoburigo

The issue is unrelated to what you are describing:

https://github.com/digoburigo/nextjs-auth-custom-oauth/blob/9132b314df5e562e2569050ad8ce9f1cfedf7cf3/.env.example#L13-L14

Just remove this, and all should be good! You linked to the old docs, new Auth.js libs very rarely need AUTH_URL anymore (not even NextAuth.js v4 to be honest)

Was discovered here: https://github.com/nextauthjs/next-auth/pull/9758#issuecomment-1908871938

balazsorban44 avatar Jan 27 '24 01:01 balazsorban44

@balazsorban44 removing the AUTH_URL from .env did not resolve the issue. Did you try to run the project to see at least? Do I have to configure something else? even with basePath: "/api/auth" still tries to make a GET request to //session

digoburigo avatar Jan 27 '24 13:01 digoburigo

@balazsorban44 I found out how to make it work for now. You have to set both basePath to /api/auth and AUTH_URL to http://localhost:3000/api/auth

digoburigo avatar Jan 27 '24 13:01 digoburigo

Neither should be needed! This is weird. I'll have a look at the repro.

(Would have loved if it was a simple codebase, not a full monorepo with a ton of unrelated code. :pray:)

balazsorban44 avatar Jan 27 '24 13:01 balazsorban44

@balazsorban44 Sorry for the monorepo, but I tried to simulate the setup of my company system, but I remove a lot of code from the repo, there is only the applicationapps/nextjs and packages packages/auth(Auth.js) and packages/oidc

digoburigo avatar Jan 27 '24 14:01 digoburigo

With these latest changes I guess everything it's working now. I updated the reproduction repo and it's working. Feel free to close this issue I guess. Thanks for the effort!

digoburigo avatar Feb 05 '24 23:02 digoburigo

I just had this same issue and deleting my NEXTAUTH_URL environment variable and either setting baseUrl or letting it default fixed it for me

Vap0r1ze avatar Feb 09 '24 22:02 Vap0r1ze

Having the same problem using 5.0.0-beta.11, I have both AUTH_URL and NEXT_PUBLIC_APP_URL due to running behind a proxy, using the standard base path. How would I solve this ?

[auth][error] UnknownAction: Cannot parse action at /session .Read more at https://errors.authjs.dev#unknownaction at parseActionAndProviderId (webpack-internal:///(rsc)/./node_modules/@auth/core/lib/utils/web.js:102:15) at toInternalRequest (webpack-internal:///(rsc)/./node_modules/@auth/core/lib/utils/web.js:35:40) at Auth (webpack-internal:///(rsc)/./node_modules/@auth/core/index.js:84:103) at getSession (webpack-internal:///(rsc)/./node_modules/next-auth/lib/index.js:20:60) at eval (webpack-internal:///(rsc)/./node_modules/next-auth/lib/index.js:93:20) at HomePage (webpack-internal:///(rsc)/./app/page.tsx:15:69)

michelbieleveld avatar Feb 18 '24 15:02 michelbieleveld

Having the same problem using 5.0.0-beta.11, I have both AUTH_URL and NEXT_PUBLIC_APP_URL due to running behind a proxy, using the standard base path. How would I solve this ?

`[auth][error] UnknownAction: Cannot parse action at /session .Read more at https://errors.authjs.dev#unknownaction at parseActionAndProviderId

I have the same issue with setting the AUTH_URL. I will like to use docker to deploy the next.js project so I have to set AUTH_URL to prevent next-auth redirecting to http://0.0.0.0:3000 as host.

My environment: Dependencies

  • next: 14.1.1-canary.61
  • next-auth: 5.0.0-beta.11 System:
  • macOS 14.3.1
  • node 20.11.0

The issues only occurred when I try to protect my page behind server side auth() in 'use server' page.tsx

const session = await auth()

I made a minimal error reproduction to show the error message when accessing http://localhost:3000/error-page https://github.com/tntchn/next-auth-sample-project/tree/unknown-action Page without server await auth() work normally as usual

tntchn avatar Feb 19 '24 07:02 tntchn

I have the same problem, trying to call it in route.ts and having same error. Same versions as you guys. Tried changing the action path /session with API URL by setting AUTH_URL, it changes it, but I get the same error.

entvia avatar Feb 19 '24 09:02 entvia

In my case setting basePath: "/api/auth", trustHost: true and finally explicitly setting secret in config resolved the issue

entvia avatar Feb 19 '24 09:02 entvia

@balazsorban44 I found out how to make it work for now. You have to set both basePath to /api/auth and AUTH_URL to http://localhost:3000/api/auth

This does work for me? If you running the server please restart the server to apply the changes; Changes: in .env file AUTH_URL="http://localhost:3000/api/auth"

in auth.js basePath:'/api/auth' image

InsafNilam avatar Feb 20 '24 13:02 InsafNilam

Having same issue, in a docker production environment. Local works fine. But, deployed I'm getting the "Cannot parse action at /session" error.

It appears the issue is in lib/env.js. The function reqWithEnvURL is attempting to create a new NextRequest object.

NextRequest class is part of Next.js server components and is designed to be used in the context of a Next.js serverless function or middleware. It's not designed to be used in a standalone Node.js script. It makes sense to reconsider the approach. Instead of creating a new NextRequest object, you can modify the req.nextUrl property directly:

` export function reqWithEnvURL(req) { const url = process.env.AUTH_URL ?? process.env.NEXTAUTH_URL; if (!url) return req;

const { origin: envOrigin } = new URL(url);
const { href, origin } = req.nextUrl;
const value = href.replace(origin, envOrigin)

req.nextUrl.href = value;
return req;

} `

This gets me to the api/auth/signin url as expected. But, there appears to be another issue upstream. When I sign in, it's redirecting me back to url with actual host/port not the functional host/port.

spatial-bit avatar Mar 05 '24 23:03 spatial-bit

I would like to suggest to @balazsorban44 to test next auth on next auth app running in the docker.

I manged to make next auth work with workaround on version beta5, with defining NEXT AUTH internal and NEXT AUTH url and unwrapping middleware, since the cookies set up on the client were then missing on the request. Without this workaround next auth sort of works out of the box, but signOut function no matter what callback url, or redirect arguments were, always redirected to the server internal address. And on the latest beta version even this workaround is not possible as wrote people above, defining envs breaks it.

bluelakee02 avatar Mar 08 '24 20:03 bluelakee02

I think we actually just added tests for docker! cc @ndom91

balazsorban44 avatar Mar 08 '24 22:03 balazsorban44

I think we actually just added tests for docker! cc @ndom91

yeah, I just checked it and maybe I would suggest to forward port in that docker compose file, to f.e. 3001 ports: - "3001:3000" and use in the playwrite localhost:3001. Then would be possible to test if the user is in some cases redirected to 3000 (bad) or is kept on 3001 (good). Just a quick idea ✌.

bluelakee02 avatar Mar 08 '24 23:03 bluelakee02

thanks @digoburigo, by setting AUTH_URL to https://foobar.com/api/auth and setting basePath: '/api/auth' finally made it work in production. I just stood up and gave you a standing ovation. 👏👏

mistersingh179 avatar Mar 14 '24 15:03 mistersingh179

I precisely had this problem with nextjs v14.1.0 when starting production using next-auth in its version ^5.0.0-beta.13 error: [auth][error] UnknownAction: Cannot parse action in /session. Read more at https://errors.authjs.dev#unknownaction

I managed to solve it by correctly adding the .env environment variable

AUTH_URL=http://localhost:3000/api/auth and ready to compile and put my web project into production

daenerys973 avatar Mar 17 '24 19:03 daenerys973

Just removing basePath: "/auth", from the demo auth.ts fixed it for me.

Not sure why that is there it's invalid.

timmeade avatar Mar 23 '24 20:03 timmeade

The basePath / AUTH_URL issues should be fixed with the latest next-auth release (5.0.0-beta.16).

Let us know if you're still having issues :+1:

ndom91 avatar Mar 25 '24 18:03 ndom91

I'm going to close this issue as the original issue was resolved. If anyone is still having issues with basePath / AUTH_URL, feel free to open a new one!

ndom91 avatar Mar 25 '24 18:03 ndom91

Dear @ndom91,

I'm currently utilizing next-auth, and it functions smoothly when I access api/auth/signin. However, I'm attempting to integrate it with next-intl. Following the next-intl documentation, I wrapped the contents of the app folder with the dynamic segment [locale]. Yet, upon navigating to en/api/auth/signin, it throws an error: [auth][error] UnknownAction: Cannot parse action at /en/api/auth/signin.

image

Environment

Dependecies: "next": "14.1.4", "next-auth": "^5.0.0-beta.16", "next-intl": "^3.11.1",

files structure

├── messages
│   ├── en.json
│   └── ...
├── next.config.mjs
└── src
    ├── i18n.ts
    ├── middleware.ts
    ├── auth.ts
    ├── navigation.ts
    └── app
        └── [locale]
            ├── layout.tsx
            ├── page.tsx
            ├── api
               └── auth
                  └── [...nextauth]
                     └── route.ts
// src/auth.ts

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
});
// src/middleware.ts

import createMiddleware from "next-intl/middleware";

import { locales, localePrefix } from "@/navigation";

export default createMiddleware({
  locales,

  defaultLocale: "ar",
  localePrefix,
});

export const config = {
  // Skip all paths that should not be internationalized
  matcher: ["/((?!api|_next|.*\\..*).*)"],
};
// src/navigation.ts

import { createSharedPathnamesNavigation } from "next-intl/navigation";

export const locales = ["ar", "en"] as const;
export const localePrefix = "always"; // Default

export const { Link, redirect, usePathname, useRouter } =
  createSharedPathnamesNavigation({ locales, localePrefix });

khaledtag98 avatar Apr 07 '24 00:04 khaledtag98

Hey yeah so if I were you I wouldn't include the api folder in the language wrapping. You don't want to translate api routes, right?

ndom91 avatar Apr 07 '24 06:04 ndom91

I will try to move it outside the language wrapping. Thank you @ndom91 for your support.

khaledtag98 avatar Apr 07 '24 14:04 khaledtag98