0

I'm using NextAuth for authentication and URQL's authExchange. The idea is to attach an accessToken in the Authorization header.

// ...
import { authExchange } from '@urql/exchange-auth'
import { getSession } from 'next-auth/react'

getAuth: async ({ authState }) => {
  // for initial launch, fetch the auth state from storage (local storage, async storage etc)
  if (!authState) {
    const session = await getSession()
    if (session && session.user.accessToken) {
      return { token: session.user.accessToken }
    }
    return null
  }
  return null
},

When I start the server, it prints [next-auth][error][CLIENT_FETCH_ERROR] https://next-auth.js.org/errors#client_fetch_error request to http://localhost:4200/api/auth/session failed, reason: connect ECONNREFUSED 127.0.0.1:4200

The error is caused by getSession(), but why does that happen and is there any potential fix?

Stephan882
  • 133
  • 2
  • 16

2 Answers2

0

It sounds like NEXTAUTH_URL env variable was either not set, or set to an incorrect url. is you local dev server running at localhost:4200?

If not, you have to update your NEXTAUTH_URL env var.

Also see https://next-auth.js.org/getting-started/example#extensibility about making the accessToken available in your session state. Theres some more work you have to do in the callbacks in your pages/api/auth/[...nextauth].js in order to have your accessToken available there where you expect it.

ndom91
  • 719
  • 1
  • 9
  • 19
  • It's already set and everything is working. This error message appears only on booting up the server. I assume `getAuth()` is called on startup when the server is still offline. – Stephan882 Mar 02 '22 at 18:06
0

I ran into a similar issue and realized that the error is thrown whenever the function is called client-side. In that case there is no request object and the getSession function throws an error.

I managed to stop the error by only providing arguments to the function if req exists:

  const sessionProps = req ? { req } : undefined;
  const session = await getSession(sessionProps);

However, for me that still does not provide me with the accessToken in the session for some reason. It seems like the accessToken is not attached to the session in my case.

Carolin
  • 121
  • 4