Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Firebase relatime database add google authenticated users

I'm trying to add users to realtime database who are authenticated using google as shown below

document.getElementById("btnGoogleLogin").addEventListener('click', function () {
    signInWithPopup(auth, provider)
        .then((result) => {
            // This gives you a Google Access Token. You can use it to access the Google API.
            const credential = GoogleAuthProvider.credentialFromResult(result);
            const token = credential.accessToken;
           
            // The signed-in user info.
            const user = result.user;
       
            const userId = user.uid;
            const email = user.email;
            const imageUrl = user.photoURL;
            const name = user.displayName;

            const dbRef = ref(database);
            console.log("Current User:" + userId);
            get(dbRef, '/users' + userId).then((snapshot) => {
                if (snapshot.exists()) {
                    console.log(snapshot.val());
                } else {
                    console.log("First time user..Need to add it to db");
                    writeUserData(userId, email, imageUrl, name)
                }
            }).catch((error) => {
                console.error(error);
            });

        }).catch((error) => {
            // Handle Errors here.
            const errorCode = error.code;
            const errorMessage = error.message;
            // The email of the user's account used.
            const email = error.email;
            // The AuthCredential type that was used.
            const credential = GoogleAuthProvider.credentialFromError(error);
            console.log(error);
        });
});


function writeUserData(userId, email, imageUrl, name) {
    set(ref(database, '/' + userId), {
        email: email,
        imageUrl: imageUrl,
        name: name
    })
        .then(() => {
            window.location.href = "https://www.mysite.default.html";
        })
        .catch((error) => {
            // The write failed...
        });
}

The problem is first time it add user under users db and when a new user who login using google is not being added to the existing users db but added in authetication.

I am not sure how to get rid of this.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First as commented by @Frank, there must be a / between 'users' and userId. Then get() takes only 1 parameter of type Query (or a DatabaseReference) but you are passing 2 and hence the get() is querying dbRef which means the entire database. The database might be empty by default and hence the first user gets added but there after snapshot.exists() would always be true and newer users are not added.

Using child() to create a DatabaseReference should resolve this:

import { child, get } from "firebase/database"

const userRef = child(dbRef, 'users/' + userId);

get(userRef).then((snapshot) => {
  if (snapshot.exists()) {
    console.log(snapshot.val());
  } else {
    console.log("First time user..Need to add it to db");
    writeUserData(userId, email, imageUrl, name)
  }
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!