Firebase Version 9 Tutorial (Modular)

Firebase Version 8 Tutorial (Namespaced)

How To Get User Data By UID Using Firebase Auth & RTDB

Last modified on June 13th, 2024
Raja Tamil
Authentication Firebase Javascript

One of the questions I have been asked a lot about Firebase is:

How to get currently logged-in user data from Firebase Real-Time Database?

Let’s see how to do that in action.

I am assuming that you already know how to create a project in Firebase, add appropriate Firebase Product SDKs, and initialization code to your project.

Recommended: Create A Firebase Project and Get Initialization Code

  • Implement Firebase Authentication
  • Add Logged In User Data
  • Get Logged In User Data
  • Protect User Data Using Security Rules

Implement Firebase Authentication

1. Add Firebase Auth SDK CDN to your HTML file.

<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-auth.js"></script>

2. Make sure to enable the Email/Password option under the Sign-in Method tab on the Firebase Authentication page.

Being lazy, I added an email and the password values hardcoded rather than getting them from HTML input elements.

var email = "raja@gmail.com"
var password = "pword1"

async function createNewAccount() {
    try {
        const user = await firebase.auth().createUserWithEmailAndPassword(email, password);
        console.log(user.uid)
    } catch (error) {
        console.log(error.message)
    }
}

When you invoke the createNewAccount() on page load, a brand new Firebase account will be created on the Firebase Authentication page.

Recommended: FirebaseUI + Vue.js: Build A Complete Social Login Page

Get User Data Using Auth() Object

As soon as a new Firebase account is created, you’re in a logged-in state and the user’s auth object is available inside the onAuthStateChange() method.

firebase.auth().onAuthStateChanged(user => {<br>  if(user) {
    console.log(user.uid)<br>    console.log(user.email)<br>   }
})

The user’s auth object will have some data about the logged-in user. If you want to add some additional information such as phone and address, you will need to store them in the real-time database.

Recommended
Learn Firebase Storage Quickly [Guide]

Add User Data To The Database

Once the userAuth object becomes available, compose a user object with properties like name, phone, address, etc including uid and email from the userAuth object.

Then, pass it to the writeUserData() function as an argument.

async function createNewAccount() {
    try {
        const userAuth = await firebase.auth().createUserWithEmailAndPassword(email, password);
        var user = {
            name: "Raja",
            phone: "779797329",
            address: "474 Mercer Drive",
            uid: userAuth.uid,
            email: userAuth.email
        }
        writeUserData(user)

    } catch (error) {
        console.log(error.message)
    }
}

This will store user data under users as a child node using uid as a push key.

function writeUserData(user) {
    firebase.database().ref('users/' + user.uid).set(user).catch(error => {
        console.log(error.message)
    });
}

If you get a permission error, make sure to have the Write Rule set to true for now from the Rules Tab on the Firebase Authentication page.

Get User Data From The Database

Let’s get the user data when the authentication stage changes into logged-in.

firebase.auth().onAuthStateChanged(user => {
    if (user) {
        getUserData(user.uid)
    }
})

Declare the getUserData() function.

function getUserData(uid) {
    firebase.database().ref('users/' + uid).once("value", snap => {
        console.log(snap.val())
    })
}

As you can see, you can easily obtain user data by passing the currently logged-in user’s uid on the database reference path.

Protect User Data

Let’s say you have a couple of users named userA and userB signed into your application.

If userA somehow gets the uid of userB, userA can steal userB’s information which is not secure. 😢

function getUserData(uid) {
    firebase.database().ref('users/' + "userB'sUID").once("value", snap => {
        console.log(snap.val())
    })
}

To protect that, you will need to have correct security rules in place at the database level.

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }
    }
  }
}

The above security rules will restrict logged-in users so that they can only read or write their own data, NOT others.

So now you have learned how to get logged-in user data using uid as well as how to protect user data.

Up Next
Learn Firebase Storage Quickly [Guide]