My experience with Vercel deployment has been quite interesting. While I find that Google authentication works seamlessly on localhost, it seems to encounter an issue when deployed on Vercel. Specifically, after logging out, the currentUser variable always returns null.
On the contrary, on my local environment, everything works perfectly. I can log in and out multiple times without any problem, and the currentUser object always contains the necessary data.
I've tried experimenting with dependencies in the useEffect hook, but unfortunately, the issue persists. I also attempted to disable the third-party storage partitioning feature in Chrome flags, but it didn't resolve the issue either.
'use client'
import { useEffect, useState, useContext, createContext } from 'react'
import { useRouter } from 'next/navigation'
import {getAuth, GoogleAuthProvider, onAuthStateChanged, signInWithRedirect} from 'firebase/auth'
import { User } from 'firebase/auth'
import '@/services/firebaseConfig'
import { DocumentData, doc, getDoc } from 'firebase/firestore'
import {auth, db} from '@/services/firebaseConfig'
import { usePathname } from 'next/navigation'
import {DEFAULT_REDIRECT_PATH} from "@/config/constants";
interface AuthProviderProps {
children: React.ReactNode
}
interface AuthContextType {
user: User | null
authLoading: boolean
userData: DocumentData | undefined
setUser: (user: User | null) => void
setUserData: (user: DocumentData | undefined) => void
}
const AuthContext = createContext<AuthContextType | null>(null)
export const useAuth = () => {
return useContext(AuthContext)
}
export const AuthProvider = ({ children }: AuthProviderProps) => {
const router = useRouter()
const [authLoading, setAuthLoading] = useState(false)
const [user, setUser] = useState<User | null>(null)
const [userData, setUserData] = useState<DocumentData | undefined>()
const pathname = usePathname()
useEffect(() => {
const auth = getAuth()
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
if (currentUser) {
const userRef = doc(db, 'users', currentUser.uid)
// const userDoc = await getDoc(userRef)
// setUser(currentUser)
// setUserData(userDoc.data())
if (['/login', '/register'].includes(pathname || '')) {
if(currentUser.emailVerified) {
router.replace(DEFAULT_REDIRECT_PATH)
}
}
}
else {
// setUser(null)
// setUserData(undefined)
}
console.log('currentUser', currentUser)
if (
!currentUser && !['/', '/register', '/legal', '/login'].includes(pathname || '')
) {
router.replace('/login')
} else {
// setAuthLoading(false)
}
})
return () => unsubscribe()
}, [user])
return (
<AuthContext.Provider value={{ user, authLoading, userData, setUser, setUserData }}>
{children}
</AuthContext.Provider>
)
}