The integration of Firebase Google Auth seems to encounter issues when used on the Vercel

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>
  )
}

Answer â„–1

Have you followed the instructions for signing in with redirect? Check out Firebase Auth Web Redirect Best Practices

To ensure proper functioning, place a vercel.json file at the root of your application (outside of src) with:

{
    "rewrites": [
      {
        "source": "/__/auth/(.*)",
        "destination": "https://redseat.firebaseapp.com/__/auth/$1"
      }
    ]
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I add navigation dots to my slider?

I've been experimenting with my slider and I managed to make it slide automatically. However, the issue is that there is no option to manually navigate through the slides. I am looking to add navigation dots at the bottom so users can easily switch be ...

I encountered an issue while attempting to install dependencies listed in the package.json file using the npm install command

npm encountered an error with code 1 while trying to install a package at path C:\Users\HP\Desktop\workings\alx-files_manager\node_modules\sharp. The installation command failed due to issues with the sharp plugin and its ...

Utilizing Google Maps API to automatically set an address on page load

As a beginner in using the Google Maps API, I have successfully integrated a Google Map into my project. However, I am struggling to figure out how to set specific addresses on the map. I have a list of 2,000 entries in a database, each including an addres ...

Looking to display several charts on a single page with varying datasets?

I have successfully integrated a doughnut chart plugin into my website. However, I would like to display multiple charts on the same page with different data sets. Below is the code snippet for the current chart being used: This is the chart I am using & ...

Extracting data from XPath results reveals information beyond just the elements themselves

Having trouble using the getElementsByXPath function in CasperJS to return a specific string from an xpath I determined. Despite my efforts, it seems like the function is only returning data for the entire webpage instead of the desired string. var casper ...

Mobile device users experiencing issues with jQuery scroll up and down functionality

Currently, I am utilizing jQuery to identify when a user is scrolling the mouse wheel up or down. Below is my code: $(window).bind('mousewheel DOMMouseScroll', function(event){ if (event.originalEvent.wheelDelta > 0 || event.originalEvent ...

Encountering a syntax error while attempting to send Node.js data to MySQL database

I am facing a problem with an SQL error that I just can't seem to figure out. Here is the error message: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual for MySQL server version for correct syntax near 'x Disney â ...

How can I use jQuery to vertically align an element?

Here's my website: Take a look here! I have a menu on the left column that I want to center. Take a look at the image below for a better understanding of what I'm trying to achieve. https://i.stack.imgur.com/ZzprT.png Here is the JavaScript c ...

When sharing content or using other tools, the dynamic metadata in Next.js 13.4 is not appearing as expected

When I visit the dynamic routes pages of my published site and try to share it on social media or check its SEO using tools like "https://metatags.io/", the metadata is not displaying. However, when I inspect the elements in Google Developer Tools, I can s ...

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...

Strategies for launching a React, Next JS, and Tailwind application

After customizing a Tailwind 'Template' site, I encountered challenges when trying to deploy it in a Production environment. The README provided clear instructions for running it locally but lacked details on deployment steps. I am seeking a deta ...

The request body parser for the express POST method appears to be devoid of

After encountering similar issues on Stack Overflow, I discovered a solution involving the use of: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); However, despite implementing this solution, the log for req.body is still ...

Ways to eliminate text following a string substitution

When running the code below with keys assigned to summer, spring, fall, and winter, the output for ins would be: ['req.body.summer, req.body.spring, req.body.fall, req.body.winter'] I need to eliminate the surrounding string from the replace co ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

`"Attempting to access keys of a non-object value" - Dealing with JSON and React Native`

Having trouble with React Native and JSON structure? No worries, we've all been there at some point! Don't sweat it if you're still new to React and JavaScript - we're here to help! Let's take a look at the JSON structure causing ...

Using jQuery to retrieve values from clicked buttons

I'm trying to retrieve the values of a jQuery button upon form submission, but my current setup is not working. Specifically, I need to extract the value of data-url. Below is the code snippet I am using: $("#addAgency").submit(function(event) { ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

Is it possible to install the lib ldap-client module in node.js?

I'm having trouble installing the lib ldap-client package in Node.js. To try and solve this issue, I consulted the following page: https://github.com/nodejs/node-gyp. In an attempt to fix the problem, I have installed python, node-gyp, and Visual St ...

Learn how to increase spacing in React applications

I'm currently utilizing the Grid component from @material-ui to present my data. Within this Grid, I have several nested grids, each representing a different section. I've implemented the container spacing attribute of the Grid and set it to the ...

I'm encountering an issue in my node application where it is unable to access the push

I am a beginner in the world of node.js and express. Whenever I try to start my application using the command npm start, I encounter an error message saying Cannot Read property push of undefined from my index.js file. The problematic code snippet looks l ...