question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

/api/auth/session returning 404 in getSession

See original GitHub issue

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 (<anonymous>) 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.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
jeremygottfriedcommented, Apr 24, 2021

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

2reactions
sheptangcommented, Aug 25, 2021

I’ve found the solution myself.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Next Auth getSession API call fails when used in ...
Looks like you didn't configure the NEXTAUTH_URL environment variable. ... toLocaleLowerCase(); session.user.uid = token.sub; return session; }, }, });.
Read more >
authClient.session.get() hitting 404 error on api/v1/sessions/me
The call to renderEl() displays the widget just fine and once the user signs in it even returns a session with status 'ACTIVE'...
Read more >
Errors - NextAuth.js
This occurs when there was an error in the POST request to the OAuth provider and we were not able to retrieve the...
Read more >
wisenickel5 - Auth0 Community
Http://localhost:3000/api/auth/me returns 404 in Console · Help · auth0, api, login, nextjs · wisenickel5 May 4, 2022, 1:46am #1.
Read more >
GetSessionToken - AWS Security Token Service
Using the temporary security credentials that are returned from the call, IAM users can then make programmatic calls to API operations that require...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found