Firebase: setting additional user properties

mm24 picture mm24 · May 24, 2016 · Viewed 16.7k times · Source

I'd like to add a property to a Firebase user object. The user documentation says that I can only store additional properties using the Firebase real time database.

I am unsure on how this can works in practice.

What does the following mean in practice?

You cannot add other properties to the Firebase User object directly; instead, you can store the additional properties in your Firebase Realtime Database.

I interpret it as following:

"you cannot modify properties of a FIRUser object but you can combine this with additional objects"

I found the set function documentation which I interpet in this way:

  var userRef = ref.child("users");
  userRef.set({
    newfield: "value"
  });

Is this a sensible approach?

Answer

Frank van Puffelen picture Frank van Puffelen · May 24, 2016

You're almost there. In the legacy Firebase documentation, we had a section on storing such additional user data.

The key is to store the additional information under the user's uid:

    let newUser = [
        "provider": authData.provider,
        "displayName": authData.providerData["displayName"] as? NSString as? String
    ]
    // Create a child path with a key set to the uid underneath the "users" node
    // This creates a URL path like the following:
    //  - https://<YOUR-FIREBASE-APP>.firebaseio.com/users/<uid>
    ref.childByAppendingPath("users")
       .childByAppendingPath(authData.uid).setValue(newUser)

I've added a note that we should add this information in the new documentation too. We just need to find a good spot for it.