How To Get User Specific Data By UID in Firebase [RTDB]

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 an appropriate Firebase Product SDKs and initialization code to your project.

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 createNewAccount() on page load, a brand new Firebase account will be created on the Firebase Authentication page.

Get User Data Using Auth() Object

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

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

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 into the real-time database.

Add User Data To The Database

Once userAuth object becomes available, compose a user object with properties like name, phone, address etc including uid and email from 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 pushkey.

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 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 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 somewhat gets a uid of userB, userA can steal userB’s information which is insecure. 😢

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 as well.