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

Issue: The observer's callback function is not being triggered when utilizing the rxjs interval

Here is a method that I am using: export class PeriodicData { public checkForSthPeriodically(): Subscription { return Observable.interval(10000) .subscribe(() => { console.log('I AM CHECKING'); this.getData(); }); } ...

Retrieving information within the iteration

I am facing an issue with connecting to an external server named Pexels in order to retrieve photos from node.js. The problem seems to be related to JavaScript, as Pexels limits the user to download up to 40 pictures per page. https://api.pexels.com/v1/cu ...

Controlling worldwide modules using Node Version Manager

Currently, I am utilizing nvm as a tool to manage node.js / io.js versions, encountering difficulties with global modules every time I update node. Recently, I attempted to install npm i express-generator -g. I noticed an older version in /usr/local/bin a ...

Learn how to retrieve URL parameters using HTML code

I would like to update the URL without refreshing the page as I am using an AJAX function to refresh a specific div. The issue I am encountering is that when the div is reloaded via AJAX, it does not recognize the URL parameter. Below is my code (I have a ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

navigation bar directing to the wrong destination

My landing page has attached pages like landing/gothere and /another. The issue arises when I try to navigate from /another to landing/gothere. I fetch landing information using an API, but there's a delay when I click on the navbar link. The page loa ...

Replacing values in an HTML file with MySql query results

----- Problem solved, solution below ----- In my HTML file, I have a dropdown menu for various courses listed as follows: <ul> <li class="dropbtn" id="1"> <a href="">first</a> <ul class="dropdown-content"> ...

utilize the flex index.html layout

Upon reviewing the template, I noticed that there is code implemented to check if the client has the necessary version. This code performs certain actions based on whether or not the required version is available. Additionally, there seems to be an <obj ...

Filtering data in Angular based on specific dates

Upon receiving data from an Angular service, I have a JSON object structured like this: [ { "id": 2, "order_status": "R", "order_date": "2015-09-12T07:58:24.733834Z", "update_timestamp": "2015-10-05T04:22:44.904227Z" ...

Divide the number by the decimal point and then send it back as two distinct parts

Let's tackle a challenging task. I have a price list that looks like this: <span class="price">10.99€/span> <span class="price">1.99€/span> My goal is to transform it into the following format: <span class="price">10< ...

What is the best way to specify a submission destination for a custom form component in Vue?

I am looking to streamline the use of a form component across my website, however, I need the submit button to perform different actions depending on which page calls the form-component. Experimenting with Vue components and data passing is new to me as I ...

Off Canvas left navigation menu using Bootstrap

I am working on creating a responsive layout for a webpage using Bootstrap. On larger displays, such as desktop resolutions, I want the webpage to show the header and left navigation as normal. However, when the site is resized to that of tablets or mobile ...

Ensure modifications to a variable are restricted within an if statement

I am struggling to find a way to globally change a variable within an if statement and ensure that the modifications persist. User input: !modify Bye var X = "Hello" if (msg.content.includes ('!modify')) { X = msg.content.replace('!modi ...

What are the steps to refreshing a table using AJAX?

Struggling to update a table from my database, I have been following a PHP guide but can't get it to work. In a separate file, the data is retrieved and displayed in a table. I am attempting to use JavaScript to refresh this file. This code snippet ...

Chrome crashing due to toDataURL

Recently, I have been working on a Tile Renderer for three.js and so far, everything appears to be functioning correctly. The process is quite simple: a) It creates multiple cameras, b) Renders the scene using each camera c) Generates a 'toDataURL&a ...

What is the best way to store information in my express server using Angular?

After spending several hours on this issue, I am feeling stuck. Initially dealing with a CORS problem, I managed to solve it. However, my goal is to utilize $resource without creating a custom post method. My API follows RESTful standards where POST /artis ...

Could using an image defer script instead of a lazy image script result in an undefined offset error?

To enhance the pagespeed of my website, Pagespeed Insight recommends using deferred images instead of lazy jQuery images. In an effort to follow this advice, I made adjustments based on suggestions from another source. Read more on stackoverflow I utiliz ...

Can you provide an example of JSON for a MultiStep Form that includes a variety of control types for viewing

Could someone please provide me with JSON examples of multi-step forms that include various types of controls such as radio buttons, checkboxes, dropdown menus, and calendars? I am in need of JSON for both the view and edit forms. Your help would be grea ...

When activated, JavaScript is producing an undefined response

This is a function with the following designer code. I have made updates to include the latest answer. function OnClientLoBChecked(sender, args) { var ChkBoxLOB = document.getElementById("<%= cbFLoB.ClientID %>"); var ChkBoxDis = document ...

Guide to sending parameters to the method function of the Vue.js router

I am encountering an issue while trying to pass 'joke.id' as a parameter to the router: edit: function(joke) { this.$router.push({ '/edit/' + joke.id }); } The specific route in question is: {path: '/edit/:id', compone ...