FireBase: Adding extra information to user on sign up and other tips

Doyin Olarewaju
2 min readJul 22, 2017

--

Firebase is great. Realtime db, functions, authentication and a whole lot of bells and whistles have been added for you. The docs are also very good, but I have seen one or two questions about some simple use cases that where not covered in the docs. So I felt i just cover how i handle them here.

This will be incremental, as I will add more tips as I remember so check back once in a while or follow me. Here goes:

Add profile info during signup

The documentation how to create new user using a plethora of methods. But i will make use of the method createUserWithEmailAndPassword. I am assuming you have initialized firebase with your credentials and you now have a firebase object

firebase.auth().createUserWithEmailAndPassword(email, password)
.then(
(user)=>{
// here you can use either the returned user object or firebase.auth().currentUser. I will use the returned user object
if(user){
user.updateProfile({
displayName: // some displayName,
photoURL: // some photo url
}).then(
(s)=> // perform any other operation
)
}
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});

What I did is after the promise for the signup completes, I make use of the user object it returns to update the profile. Its pretty self explanatory. So there you go.

Get current user

You would think to get current user what you need to do is firebase.auth().currentUser right ? Wrong!!!

I actually admire how this is handled, but i don’t feel its intuitive enough especially for devs coming from a php background. Why I feel it works like this is because database is realtime and a lot could change in so little time. So we need a listener to determine if the user has taken any authentication action. The correct way to handle this is to use the onAuthStateChanged. This will listen to any authentication state change for the current user and you can also get the user’s profile information.

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});

After the information has been fetched you can use it however you deem fit.

Stay tuned for more tips or visit the firebase docs for more info at https://firebase.google.com/docs/ . Thanks.

--

--