Next.js Discord

Discord Forum

Next-auth error after 2 years and no significant changes

Unanswered
Welsh Springer Spaniel posted this in #help-forum
Open in Discord
Avatar
Welsh Springer SpanielOP
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'}
Image

30 Replies

Avatar
Welsh Springer SpanielOP
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
        },
    }
})
Avatar
Bigeye tuna
Didin't investigate it deeply but in my case I accidentaly changed basePath for SessionProvider

"use client";

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
Avatar
Welsh Springer SpanielOP
my setup looks like this. It's been so long I totally forget what this does lol.
                    <SessionProvider session={pageProps.session}>
                        <Layout>
                            <Component {...pageProps} />
                            
                        </Layout>
                    </SessionProvider>
Avatar
Bigeye tuna
Try setting basePath="/api/auth"
as a SessionProvider prop
Avatar
Welsh Springer SpanielOP
No difference :l what should my basePath be targeting?
Image
also, i'm getting this error on production
Image
Avatar
Bigeye tuna
What version of next/next-auth are you using
Avatar
Welsh Springer SpanielOP
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 {
"^4.24.3"
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...
Avatar
Welsh Springer SpanielOP
was able to get this error to show up in my terminal
Image
Avatar
Welsh Springer SpanielOP
Image
Avatar
Welsh Springer SpanielOP
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
Image
Avatar
Welsh Springer SpanielOP
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
Image
It still says fbLoginToken (firebase login token) is null though.
Image
Avatar
Welsh Springer SpanielOP
If anyone has any ideas, please let me know 🙂
Avatar
ReverseGem7
Avatar
Welsh Springer SpanielOP
I believe I tested that out a long time ago. Not sure why I didn’t chose it as the solution, but it still doesn’t explain what changed suddenly
Avatar
Welsh Springer SpanielOP
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
Avatar
TimTucker
-+-+
Avatar
Welsh Springer SpanielOP
What’s that mean 😂
Avatar
Welsh Springer SpanielOP
forgive me father for i have bumped
Avatar
Welsh Springer SpanielOP
Update: the website is working again with no changes. Eternally confused 😐