nextauthjs / next-auth

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

useSession & hard coded '/api/auth/' route #8255

Closed leepowellnbs closed 2 weeks ago

leepowellnbs commented 1 year ago

Environment

System: OS: macOS 13.5 CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz Memory: 250.55 MB / 32.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 19.8.1 - /usr/local/bin/node Yarn: 1.22.19 - /usr/local/bin/yarn npm: 9.5.1 - /usr/local/bin/npm Watchman: 2023.03.27.00 - /usr/local/bin/watchman Browsers: Chrome: 115.0.5790.170 Safari: 16.6

Reproduction URL

https://github.com/nextauthjs/next-auth/blob/60c5037ee1dd7b11f180e83de74b66aab88d4c47/packages/next-auth/src/react/index.tsx#L133C3-L142C49

Describe the issue

The React useSession hook has a hard coded API route which means it does not play nice with a custom base path / pages etc. Could this be configurable?

React.useEffect(() => {
    if (requiredAndNotLoading) {
      const url = `/api/auth/signin?${new URLSearchParams({ <---  hard coded to api/auth
        error: "SessionRequired",
        callbackUrl: window.location.href,
      })}`
      if (onUnauthenticated) onUnauthenticated()
      else window.location.href = url
    }
  }, [requiredAndNotLoading, onUnauthenticated])

How to reproduce

See code above

Expected behavior

This should take into account NEXTAUTH_URL and/or basePath settings in the provider.

Juanchote commented 11 months ago

yes, please, not being able to define a custom route or basepath or something like that makes my api quite inconsistent.

Now I have 2 paths: api/v1/x for all my routes /api/auth for next-auth Not having semantic versioning is giving me itching.

rlaphoenix commented 10 months ago

+1 This is a stupidly ridiculous design, especially considering the docs state:

Technically, in a Route Handler, the api/ prefix is not necessary, but we decided to keep it required for an easier migration.

(source)

Tomaszal commented 8 months ago

It would be great to be able to specify a custom pathname for (Next)Auth.js, especially considering that the Next.js app router now allows safe collocation, which depending on your preferences can mean that splitting API routes into separate folders might be undesirable.

ThangHuuVu commented 2 weeks ago

hello, sorry for the delayed response - I'm closing this issue since it should be fixed in the latest version - the useSession hook now uses the __NEXTAUTH.basePath value which is the path of NEXTAUTH_URL

https://github.com/nextauthjs/next-auth/blob/b8d424ac9cff9695f90098a4b3bcba555b7cb3b3/packages/next-auth/src/react.tsx#L151

Feel free to open a new issue if you are still having problems with this code, thanks!