/firebase-tutorials

How to store additional user data in Firebase auth?

Step-by-step guide to storing extra user data in Firebase Auth. Learn to set up Firebase, authenticate users, and integrate Firestore for CRUD operations.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to store additional user data in Firebase auth?

 

Step 1: Set Up Firebase in Your Project

 

To get started, ensure that you have a Firebase project set up. If not, create one on the Firebase Console.

Download the necessary configuration files for your platform.

Add Firebase to your project by including Firebase SDKs.

For web applications, add the Firebase SDK:

<!-- The required Firebase libraries -->
<script src="https://www.gstatic.com/firebasejs/YOUR_VERSION_NUMBER/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/YOUR_VERSION_NUMBER/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/YOUR_VERSION_NUMBER/firebase-firestore.js"></script>

For Node.js environments, install necessary packages:

npm install firebase

Initialize Firebase in your application:

// For web apps
var firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.appspot.com",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

firebase.initializeApp(firebaseConfig);

 

Step 2: Authenticate Users

 

Authenticate users using Firebase Authentication. You can use email/password, Google Sign-In, or any other provider.

For email/password authentication:

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then((userCredential) => {
    var user = userCredential.user;
    // User created
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // Handle errors
  });

You can use a similar method for sign-in:

firebase.auth().signInWithEmailAndPassword(email, password)
  .then((userCredential) => {
    var user = userCredential.user;
    // User signed in
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // Handle errors
  });

 

Step 3: Store Additional User Data

 

Once a user is authenticated, you can store additional information in Firestore, a scalable database offered by Firebase.

First, initialize Firestore:

var db = firebase.firestore();

After a user is created, store additional data:

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then((userCredential) => {
    var user = userCredential.user;
    // Add additional data in Firestore
    return db.collection('users').doc(user.uid).set({
      name: 'User Name',
      age: 30,
      additionalField: 'Additional Data'
    });
  })
  .then(() => {
    console.log('User data stored');
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.error('Error: ', error);
  });

 

Step 4: Retrieve User Data

 

To retrieve stored user data, you need to access Firestore:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    var uid = user.uid;
    var docRef = db.collection('users').doc(uid);

    docRef.get().then((doc) => {
      if (doc.exists) {
        console.log('User data: ', doc.data());
      } else {
        console.log('No such document!');
      }
    }).catch((error) => {
      console.log('Error getting document:', error);
    });
  } else {
    // No user is signed in.
  }
});

 

Step 5: Update User Data

 

To update user data, use the update method in Firestore:

var user = firebase.auth().currentUser;
var updateRef = db.collection('users').doc(user.uid);

updateRef.update({
  name: 'Updated Name',
  age: 31
})
.then(() => {
  console.log('User data updated');
})
.catch((error) => {
  console.error('Error updating document: ', error);
});

 

Step 6: Delete User Data

 

If you need to remove user data, use the delete method:

var user = firebase.auth().currentUser;
var deleteRef = db.collection('users').doc(user.uid);

deleteRef.delete().then(() => {
  console.log('User data deleted');
}).catch((error) => {
  console.error('Error removing document: ', error);
});

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022