Firebase User Becomes Undefined Upon Refreshing the Web Page

My situation is quite straightforward. I have developed a Firebase web application and I am logging in with my Google account. The problem arises when I have to keep logging back in every time the page is refreshed, as depicted in these steps:

  • Initialize Firebase
  • Sign up using Google
  • Check the current user - it shows an authenticated Google user
  • Refresh the page
  • Initialize Firebase again
  • Check the current user - it displays as undefined

The code snippet provided is fairly simple:

firebase.initializeApp(config);
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider);
...
public onAuthStateChanged(context: any, user: any) {
        if (user) { ...
...
//currentUser is defined
get currentUser(): any {
    return firebase.auth().currentUser;
}

When you refresh the page:

//currentUser becomes undefined
get currentUser(): any {
    return firebase.auth().currentUser;
}
...
if(!currentUser) {
    firebase.auth().signOut();
    firebase.initializeApp(config);
}

I am aware of the options regarding persistence of Firebase sessions, but it seems that this behavior is not the default setting. You can refer to the documentation for more information:

https://firebase.google.com/docs/auth/web/auth-state-persistence

As a precautionary measure, I have added this line to my code, although it doesn't seem to make a difference:

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)

I have also confirmed that the same issue occurs with Anonymous authentication.

Answer №1

Whenever the function signInWithPopup(...) is executed, a pop-up window will appear prompting the user to sign in. It is important to only call this method when you determine that the user is not already signed in. One way to achieve this is by calling it within the onAuthStateChanged callback:

firebase.initializeApp(config);
var provider = new firebase.auth.GoogleAuthProvider();

...

public onAuthStateChanged(context: any, user: any) {
    if (user) { 
        console.log(user);
        ...
    }
    else {
        firebase.auth().signInWithPopup(provider);
    }
    ...
}

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

Angular library is being excluded from the R.js optimizer process

I'm encountering difficulties when trying to optimize an Angular project with the r.js optimizer. Everything works smoothly when I use grunt-requirejs for optimization, but as soon as I attempt to exclude Angular from the build, I encounter an error ...

The JSON response from Ajax is not coming back as anticipated

My attempts to make a basic ajax call are failing; var getPrevious = function(){ console.log('ajaxing'); $.ajax({ type: 'GET', dataType: "json", url: 'http://'+DOMAIN+'/previous', ...

Advantages of using index.js within a component directory

It seems to be a common practice to have an index file in the component/container/module folders of react or angular2 projects. Examples of this can be seen in: angular2-webpack-starter react-boilerplate What advantages does this bring? When is it recom ...

Using AngularJS to dynamically populate a dropdown menu from a JSON object

I am a beginner to Angular and currently facing my first significant challenge. The JSON object below is the address data retrieved from a third-party API and added to $scope.AddressData in a controller: $scope.AddressData = [{ "Address1":"South Row", ...

What alternative methods can be used to render a React component without relying on the ReactDOM.render

Can a React component be rendered simply by referencing it with its name? For example: <div> <MyComponent/> </div> In all the tutorials and examples I've seen, ReactDOM.render function is used to render the component onto the ta ...

Request financial data from AlphaVantage using PHP

I'm currently working on utilizing the alphavantage API to retrieve currency exchange information. In order to obtain the desired data, I am using the following query URI: https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_cu ...

Next.js: Extracting the Value of an HTTP-only Cookie

While working on my web app with Next.js, I implemented authentication management using HTTP-only cookies. To set a cookie named token, I utilized the following code snippet with the help of an npm package known as cookie: res.setHeader( "Set-Coo ...

Retrieve the latency of the interaction.reply() method

While there have been many inquiries regarding how to create a ping command for a discord.js bot, my question stands out because I am attempting to develop this command for interaction rather than message. I attempted utilizing Date.now() - interaction.cre ...

Verify the functionality of the input fields by examining all 6 of them

I'm facing a challenge with a validation function in my project that involves 6 input fields each with different answers. The inputs are labeled as input1 to input6 and I need to verify the answers which are: 2, 3, 2, 2, 4, and 4 respectively. For e ...

Retrieving HTML Content with Ajax

Currently using this script for an assignment in my class. Still learning! The script checks whether a site is down or not. I want to expand this script to display statuses for each website in the table without duplicating the script. Any suggestions on ...

The Route.get() function in Node.js is expecting a callback function, but instead received an unexpected object of type

Recently, I started coding with nodejs and express. In my file test.js located in the routes folder, I have written the following code: const express = require('express'); const router = new express.Router(); router.get('/test', (req ...

Implement various actions when the window is resized

The carousel code I have found returns a different number of items to display based on screen size. You can check it out here. $(function() { var mini = 1000; var big = 1280; if (window.screen.availWidth < mini) { $('#carousel1').jsCar ...

"Troubleshooting async/await issue with Node.js Sequelize and configuring the connection

function credential(secretFromVault) { const creddetails = new ClientSecretCredential(clientId, tenantId, clientSecret); // Build the URL to reach your key vault const url = `https://<vaultName>.vault.azure.net/`; // Lastly, create our secre ...

Avoid working on the script for the element in the partial view during the event

In my index.cshtml view, I have a script that triggers an AJAX call when the SearchingManagerId2 element is changed. $("#SearchingManagerId2").on("change", function () { var valueForSearch = $(this).val(); $.ajax({ ...

Is there a way to make a React Component to update and navigate to a specific position using react-sound

Currently, I am in the process of constructing an audio player utilizing react-sound. One feature I aim to incorporate is the ability to return to a specific position within the audio track. At the moment, this is my approach: goToVeryCustomPosition() { ...

There seems to be a syntax error lurking within npm.js, and for some reason npm insists on utilizing version 10.19.0 of Node.js despite my attempts to update it. The reason behind this behavior

Apologies if this question seems silly, but just a couple of days ago my code was running perfectly fine. Then today when I tried to load it, I encountered all sorts of errors. I am fairly new to node and npm, so I suspect it could be related to version ma ...

steps to attach click event to row of a-table component in ant design vue

Here is the code snippet for the table I am working on. I have imported a-table from antd. To enable click functionality to route to a details page from this listing page, an additional td can be added. <a-table :columns="companiesColumns" :d ...

Steps for generating random numbers from a set of given numbers

I am faced with a scenario where I need to generate random numbers based on a given set of numbers. For instance, if I have an array num=[23,56,12,22], I would like to obtain a random number from this array. ...

Please ensure that the form is only submitted when at least one checkbox is selected by utilizing JavaScript

When I visit the following form: Upon filling out the details and clicking submit, if I forget to check a checkbox, a prompt appears stating "please select any one checkbox" with an 'ok' button. After clicking 'ok', the form is then su ...

Changing the Position of HTML Scripts in React

I am facing an issue where I need to relocate an external script within a specific section of my page. However, I am unable to access the CSS attributes associated with this item. It seems that it is displayed as an iFrame, making it difficult to modify th ...