#Next-auth error after 2 years and no significant changes

31 messages · Page 1 of 1 (latest)

shrewd light
#

Hey all. I haven't worked on this website's back end in quite a long time. Basically since I initially deployed it back in 2022. I also haven't made a deployment for the past month. Today the restricted routes give me a 500 error.

I have a route thats restricted to authorized accounts. I ended up doing it in a really janky way by giving the Firebase database read and write privilege only to accounts with a hardcoded Google account UID. In addition, i restricted the ability to login to emails matching our domain. I totally forget how I did that, but that part seems to still be functioning correctly.

The issue occurs in both production and dev. I'll do my best to provide as much info, any help would be greatly appreciated

import { useSession, getSession, signIn, signOut as nextSignOut } from "next-auth/react"
import { getAuth, signInWithCustomToken, signOut as fbSignOut } from "firebase/auth";
import { useEffect } from "react";



const Dashboard = () => {
  const { data: session } = useSession({
    required: true,
    onUnauthenticated() {
    signIn()
    }
  })

  const auth = session ? getAuth() : null
    if (!session) {
      signInWithCustomToken(auth, session.fbLoginToken) 
    } 

  return (
  <Component />
  )
}
export async function getServerSideProps(context) {
  return {
    props: {
      session: await getSession(context),
    },
  }

The session object returns as null after calling useSession() which I don't think was the case before.

I tried accessing a child route on production, this time it actually forwarded me to the login route but clicking on the login button re-routed me to the same page. I was able to get this error to show up which seems like progress 🤣 :

[next-auth][error][CLIENT_FETCH_ERROR] 
https://next-auth.js.org/errors#client_fetch_error Failed to fetch {error: {…}, url: '/api/auth/providers', message: 'Failed to fetch'}
junior forgeBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

shrewd light
#

I've also tried removing the hardcoded UID restrictions from Firebase but it made no difference.

Here is the [...nextauth.js] setup. Sorry if its total crap...

#
import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import {admin} from '../../../firebase/adminDB'

const firebaseAdmin = admin.app().auth()

export default NextAuth({
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET
        })
    ],
    jwt: {
        encryption: true
    },
    useSecureCookies: true,
    secret: process.env.NEXTAUTH_SECRET,
    callbacks: {
        redirect({url, baseUrl}) {
            return url
            if (url.startsWith(baseUrl)) return url
            // Allows relative callback URLs
            else if (url.startsWith("/")) return new URL(url, baseUrl).toString()
            return baseUrl
        },

        async jwt({ token, user, account, profile, isNewUser }) {
            const fbToken = {
                uid: token.sub,
                name: token.name,
                email: token.email
            }
            console.log(fbToken.uid)
            
            firebaseAdmin.getUser(fbToken.uid)
            .then((user) => {
                !user && firebaseAdmin.createUser(fbToken).then(() => {
                    firebaseAdmin.setCustomUserClaims(fbToken.uid, {admin:true})
                })    
            })
      return token
    },
        
        async session({ session, token, user }) {

            const additionalClaims = {
                admin: true,
            }
            
            const fbLoginToken = await firebaseAdmin.createCustomToken(token.sub, additionalClaims)
            .then((customToken) => {
                return customToken
            })
            .catch((error) => {
                console.log('Error creating custom token:', error);
            })

            if (fbLoginToken) {
                session.fbLoginToken = fbLoginToken
            }

            session.token = token
            return session
        },
    }
})
kindred garden
# shrewd light Hey all. I haven't worked on this website's back end in quite a long time. Basic...

Didin't investigate it deeply but in my case I accidentaly changed basePath for SessionProvider


import {SessionProvider} from "next-auth/react";

export default function NextAuthSessionProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  return <SessionProvider basePath="/api">{children}</SessionProvider>;
}

Changing that line:
return <SessionProvider basePath="/api">{children}</SessionProvider>; helped

shrewd light
kindred garden
#

Try setting basePath="/api/auth"

#

as a SessionProvider prop

shrewd light
#

also, i'm getting this error on production

kindred garden
#

What version of next/next-auth are you using

shrewd light
#

Ok so I was able to just trigger the signIn() function, but the session never seems to be resolved.

if (!session) {
        
        signIn('google', { callbackUrl: 'urlhere' })
        return (
            <div>unauthenticated</div>
        )
    } else {
shrewd light
#

my last deployment was like a month ago though. i cant see how a dependency shipment could be forced

#

I added a signIn callback to see if its even firing. No logs in my terminal or client side console 😔 what is going on...

#

was able to get this error to show up in my terminal

#

Also some more information that might help anyone who sees this. I just realized, but while logged into chrome on the authorized accounts, I get the 500: internal server error. While in an incognito browser or another non authorized account, i get redirected to log in as expected. (this is in production)

#

this error shows in vercel

shrewd light
#

I tried rebuilding the project, no effect 😦

#

So i just figured out that although navigating to some child routes gives me the option to log in, navigating to /parentroute/dashboard shows my login credentials before throwing the 500 internal server error screen

#

It still says fbLoginToken (firebase login token) is null though.

#

If anyone has any ideas, please let me know 🙂

south dagger
shrewd light
#

On dev I’m able to get the restricted pages to load by removing the authentication completely. So authentication does seem to be the cause of the 500 code as far as I can tell. I pushed some console logs to production and found out that auth is indeed firing and receiving a session object. Which makes me indefinitely more confused

vernal bridge
#

-+-+

shrewd light
shrewd light
#

forgive me father for i have bumped