Data Missing After JSON.stringify A Firebase Object

I have an app linked to firebase. When a user logs in, I assign his object firebase.auth().currentUser to a variable. Then, I add a property (username) to that variable . The thing is that when I console.log(currentUser) I get the object with the added property. But, when I try to JSON.stringify it then JSON.parse it again (i do this to store it on localStorage) I can't find my property username that I added. What's happening here ?

var currentUser = firebase.auth().currentUser

currentUser.username = 'Foo';

console.log(currentUser) // => i get my prop username here

console.log(JSON.parse(JSON.stringify(currentUser))) // => i cant find my added prop here


currentUser is not a plain object, it is an instance of the User class. As you can see, it implements a toJSON() method which is automatically detected and used by JSON.stringify as the canonical way to transform the object into JSON.

If you want to merge custom properties onto a Firebase user, you could just add toJSON() first:

var currentUser = firebase.auth().currentUser.toJSON();

this will translate the User object into a plain object which would then be able to have additional properties added and still serialize as expected. Note, however, that this obviously won't persist on the user either server-side or on firebase.auth().currentUser.