nextauthjs / next-auth

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

/api/auth/session returning 404 in getSession #1835

Closed jeremygottfried closed 3 years ago

jeremygottfried commented 3 years ago

Describe the bug I have been using next-auth without issue for months and it suddenly stopped working today. I haven't changed any configs.

I am able to log in, but getSession throws an error. I added some logs within the node module and found that the error is a 404 when trying to fetch /api/auth/session. However, that endpoint works without issue when I fetch from the browser.

Here are my logs with the error. I added some console logs to the internal _fetchData2 function in the NextAuth client.

BASEURL http://localhost:3000/api/auth OPTIONS { headers: { cookie: 'next-auth.csrf-token={csrf-token}; next-auth.callback-url=http%3A%2F%2Flocalhost%3A3000; next-auth.session-token={session-token}' } } RES Response { size: 0, timeout: 0,

body: PassThrough {
  _readableState: [ReadableState],
  readable: true,
  _events: [Object: null prototype],
  _eventsCount: 6,
  _maxListeners: undefined,
  _writableState: [WritableState],
  writable: true,
  allowHalfOpen: true,
  _transformState: [Object],
  [Symbol(kCapture)]: false
},
disturbed: false,
error: null

},

url: 'http://localhost:3000/api/auth/session',
status: 404,
statusText: 'Not Found',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0

} } [next-auth][error][client_fetch_error] https://next-auth.js.org/errors#client_fetch_error session FetchError: invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected token < in JSON at position 0 at runMicrotasks () at processTicksAndRejections (internal/process/task_queues.js:97:5) { message: 'invalid json response body at http://localhost:3000/api/auth/session reason: Unexpected token < in JSON at position 0', type: 'invalid-json' }

Here is what the response looks like when I fetch from the browser:

{"user":{"name":"{my-name}","email":"{my-email}","image":"{my-profile-image}"},"accessToken":"{access-token}","expires":"2021-05-24T00:26:33.450Z"}

Steps to reproduce

// pages/api/auth/[...nextauth].js
const handler = (req, res) => NextAuth(req, res, {
  debug: true,
  providers: [
    Providers.Google({
      clientId: process.env.GOOGLE_OAUTH_CLIENT_ID,
      clientSecret: process.env.GOOGLE_OAUTH_CLIENT_SECRET
    }),
  ],
  adapter: Adapters.Prisma.Adapter({ prisma }),
  // SQL or MongoDB database (or leave empty)
  database: process.env.DATABASE_URL,
  site: process.env.NEXTAUTH_URL
})

export default handler;
// pages/index.js
export async function getServerSideProps(context) {
  // THIS CAUSES THE ERROR
  const session = await getSession(context);

  if (!session) {
    return {
      redirect: {
        destination: '/api/auth/signin',
        permanent: false,
      },
    }
  }
  console.log('SESSION', session);

  return {
    props: {}
  }
}

Expected behavior I expect to be able to get the session.

Additional context This has been working correctly up until now.

jeremygottfried commented 3 years ago

Nevermind. It worked after restarting my computer, so must have been a stray process.

dendisuhubdy commented 3 years ago

@jeremygottfried I got the same exact problem

sheptang commented 3 years ago

I've found the solution myself.

jeremygottfried commented 3 years ago

@sheptang what was your solution? I've run into a similar issue multiple times and still not sure what's causing it. It only happens in development, and works after restarting my computer, so I'm guessing its a stray process or a caching issue.

sheptang commented 3 years ago

Hello, I'm sorry for giving you empty hopes, it was just a reference to how useless and ego-powered StackOverflow is. If you want, check my answers and you'll see what I mean. https://stackoverflow.com/users/4775141/sheptang?tab=profile Also, I've done research about that issue everywhere i could look and i still couldn't find a solution. NextAuth is so useful with its ease of session management, tab syncing and all the other delicious things, but it's so confusing and not flexible that you just have to use whatever it has to provide to be able to achieve those things. So, actually I'm thinking that I should move on from NextAuth and switch to using several independent libraries, because I'm handling the sign-in and sign-up system all by my custom setup. I just needed it to handle the security stuff with sessions and all, but i guess I can't use only that parts of NextAuth. Sad.

balazsorban44 commented 3 years ago

@sheptang you are more than welcome to find an alternative. And you are most welcome to start discussing the things/suggestions in a constructive way in separate issues. What do you actually miss, what is unclear how you could customize, etc?

This project is a collaborative effort and we strive to provide what the users need from beginner to advanced usecases. 😊🙏

balazsorban44 commented 3 years ago

@jeremygottfried you reopened this issue without further reproduction or information, and it sounds like you have a different problem than the original one. If the problem still exists, I kindly ask you to open a new bug report with a minimal reproduction.

jeremygottfried commented 2 years ago

@sheptang (and anyone else) if you are looking for a more flexible alternative, try using express-session with passport. It gives you a lot more flexibility and the ability to have username/password login. The only drawback is you'll need to use a custom server in nextjs, but not that hard to set up. I agree next-auth is overly opinionated and restrictive, though it's a good option for building a proof of concept app.

UilquerDaniel commented 1 year ago

Olá para contribuir, tive o mesmo problema, porém no meu caso eu estava rodando dois projetos, um em localhost:3000 e um em uma porta aleatória gerada pelo próprio nuxt, então esse projeto com a porta aleatória estava dando problema, tudo por que por padrão ele gerava a requisição para a porta 3000 e ela não existia nesse segundo projeto.

ondrejpazourekdek commented 8 months ago

For \@sidebase/nuxt-auth users. In file: .\node_modules\@sidebase\nuxt-auth\dist\runtime\composables\authjs\useAuth.mjs find onError() in getSession() and add console.log(error).

const onError = ( { error } ) => { // or log whole context 
    console.log("onError", error);
    loading.value = false;
};