sidebase / nuxt-auth

🔐 Nuxt user authentication and sessions via authjs (next-auth), local and refresh providers. nuxt-auth wraps NextAuth.js to offer the reliability & convenience of a 12k star library to the nuxt 3 ecosystem with a native developer experience (DX)
https://sidebase.io/nuxt-auth/
MIT License
1.13k stars 134 forks source link

Unable to use getServerSession in server api route that starts with /api/auth #535

Open chriscdn opened 9 months ago

chriscdn commented 9 months ago

Environment


Reproduction

No response

Describe the bug

I created a /server/api/ set of endpoints for connecting and disconnecting existing social accounts. I placed these files in a directory named /server/api/auth-connect. In these files, the getServerSession returns undefined since the api route (/api/auth-connect/) starts with the string /api/auth.

I traced the problem to the getServerSession method:

export const getServerSession = async (event) => {
  const authBasePath = useRuntimeConfig().public.auth.computed.pathname;
  if (event.path && event.path.startsWith(authBasePath)) {
    return null;
  }

  // .....
};

In my instance, authBasePath resolves to /api/auth. Since event.path resolves to /api/auth-connect/, the check passes and therefore returns null.

I can't comment on why this check is necessary, but doubt all routes that start with auth should be excluded from using this method.

Additional context

No response

Logs

No response

adesousa commented 9 months ago

Same here ... 2 days, I'm raging against the version trying to find something ! And here is @chriscdn finding the exact same problem !

In my case I changed the base url to baseURL: '/api/admin/auth' and got same problem.

The try catch gave me this information:

statusCode: 500, fatal: false, unhandled: false, statusMessage: 'Tried to get server session without setting up an endpoint to handle authentication (see https://github.com/sidebase/nuxt-auth#quick-start)', data: undefined }

adesousa commented 9 months ago

As a workaround I decided to change getServerSession by :

const authBasePath = useRuntimeConfig().public.auth.computed.pathname
const session = await $fetch(authBasePath + '/session', {
    method: 'GET',
    headers: event.headers
  })

It's working fine so far. 🚀