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

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

Closed
jeremygottfried opened this issue Apr 24, 2021 · 11 comments
Closed

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

jeremygottfried opened this issue Apr 24, 2021 · 11 comments
Labels
bug Something isn't working

Comments

@jeremygottfried
Copy link

jeremygottfried commented Apr 24, 2021

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,
[Symbol(Body internals)]: {
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
},
[Symbol(Response internals)]: {
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 jeremygottfried added the bug Something isn't working label Apr 24, 2021
@jeremygottfried
Copy link
Author

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

@dendisuhubdy
Copy link

@jeremygottfried I got the same exact problem

@sheptang
Copy link

I've found the solution myself.

@jeremygottfried
Copy link
Author

@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
Copy link

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
Copy link
Member

@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
Copy link
Member

balazsorban44 commented Sep 12, 2021

@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
Copy link
Author

@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
Copy link

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
Copy link

ondrejpazourekdek commented Jan 8, 2024

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;
};

@estani
Copy link

estani commented Jan 11, 2025

I had the same issue, though I'm using the v5 beta as recommended by next.js.
Following the next.js tutorial on authentication I only created the middleware... so probably getSession() will never work in this setup, though I see nothing in the documentation...

It took me a while to figure where the documentation is, because everything I got was outdated (aka wrong, and the error messages not useful at all). I finally got it working by following the documentation of the beta version in the
repo. Basically export the handlers of the NextAuth object:

# e.g. in auth.ts, export the handlers too.
export const { auth, signIn, signOut, handlers } = NextAuth({...})
# create app/api/auth/[...nextauth]/route.js where you will export the GET and POST of these handlers
import { handlers } from "@/auth"
export const { GET, POST } = handlers

Hope this help save some time...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

7 participants