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

Using jQuery to select a nested element in HTML

After choosing $("a.tp[programm='" + programm + "']"); I am looking to target the nested element span.thump and update its text content. How can I achieve this? <h4><a programm="74" class="tp" href="#"><img src="/images/tuo.png ...

Consumer using ActiveMQ-Stomp is not receiving any messages

I attempted to create a JavaScript code for an ActiveMQ subscriber that would subscribe to a specific topic, but unfortunately I am not receiving any messages after establishing the connection. The topic that needs to be subscribed to is COO.2552270450083 ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

Sending a parameter value when onClick function is called

Currently, I am learning React JS and facing a challenge with passing parameters (like button ID or tab value) to the Tab onClick event. It appears that I'm receiving 'undefined' results when trying to pass attribute names as parameters. Ple ...

What is the best jQuery library to add to my website?

I have included several jQuery scripts on my website for various functionalities such as sticky header, anchors, and animations. I am wondering if it is necessary to include all of them or if I can just include one or two? Here are the jQuery scripts I ha ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...

Process for arranging an array according to the sorting sequence of another

Using two arrays in a Highcharts "series" parameter, for example: X = [25, 100, 50, 12] Y = [50, 12, 100, 25] The sequence of X and Y corresponds to the chart's Y value. When sorting X in ascending order, Y's order should match by becoming: X ...

The .angular-cli.json file is causing issues with loading scripts

I have recently updated my .angular-cli.json file by adding new scripts in the following format: "apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html ...

What steps can be taken to resolve the Uncaught TypeError issue with vue-router?

I am currently in the process of upgrading my Vue 2 project to Vue 3. However, I keep encountering errors consistently. The latest error message displayed on my console is as follows: vue-router.mjs:3499 Uncaught TypeError: Cannot read properties of undef ...

Switch div and expand/shrink the rest

Apologies for what might seem like a trivial question, but after working for a few hours now, I'm finding it difficult to wrap my head around this. My initial instinct is to handle this by manipulating the entire div structure with JavaScript, but I c ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

Ways to boost memory capacity in nodejs

I've been attempting to increase the memory limit in node.js, and to do so I added an environment variable. You can see how I did it here Unfortunately, it doesn't seem to be working as expected. I even tried using capital letters with no succe ...

When I attempt to connect to my local MongoDB database, including a specific port in the URI is preventing the connection from being

While testing a connection to a local DB using mongoose and mongodb, I encountered an issue. Whenever I include a port number in the URI passed to mongoose.connect(), I receive a connection refused error. async function connectDB() { const db = await m ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

When executed through nodeJS using the `require('./main.ts')` command, TypeScript Express encountered an issue with exporting and displayed undefined

Describing my issue is proving to be challenging, so I have simplified the code. Let me share the code below: main.ts import express from 'express'; let a = 1 console.log ('a in main.ts', a) export let b = a const app = express() let ...

Is there a way to effortlessly append a slug to my URL in a Node.js platform?

Currently facing challenges with my templates. As I develop an e-commerce platform, I am using a json file containing product details to create cards for each product. Due to the large number of products, creating individual pages for each one is not feas ...

Transforming the date format in VUE-JSON-EXCEL

Is there a way to change the date format for the VUE-JSON-EXCEL library? When I click the generate excel button, the date format displayed in the excel is "2022-06-10T18:18:34.000Z" instead of "10/6/2022 18:18:34" I have tried using moment.js but it is n ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Having trouble getting Ajax to function properly with CodeIgniter

Here is the AJAX code snippet: $.ajax({ url: '<?php echo base_url(); ?>deleteRowUsingApiKey/index', //This is the current doc type: "POST", //dataType:'json', // add json datatype to get json data: {name ...