Create User Profile In Firestore After Authentication in Firebase

When a user signs up for your app, Firebase creates their profile in Firebase Authentication. This is great because most of the hard stuff like OAuth and validation is being handled automatically for you.

This, however, has its limitations. Auth doesn’t let you store any custom properties to the user and this is very limited in scope.

What if you want to store more information about the user whenever they perform an action on your app?

This is where the requirement of creating user profiles upon sign up comes into play.

Whenever a user signs up on your app, you can use the auto-triggering Firebase Cloud Functions to create their profile in the database.

In this tutorial, I will be using the Cloud Firestore, but the same concepts apply to the Realtime Database too if you are using that.

Auto-triggering Functions

Firebase auth has two events for which we can create Cloud Functions.

  1. onCreate()
  2. onDelete()

Whenever a user signs up on your app, (be it email, OTP, or a 3rd party) Firebase triggers the onCreate function automatically.

When a user deletes their account, Firebase triggers the onDelete function.

For this example, we will be focusing on the onCreate() function because this is the trigger which you can use to create a user profile in the Cloud Firestore.

In your index.js, add a function as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

const db = admin.firestore();

/**
* Creates a document with ID -> uid in the `Users` collection.
*
* @param {Object} userRecord Contains the auth, uid and displayName info.
* @param {Object} context Details about the event.
*/
const createProfile = (userRecord, context) => {
return db.collection('Users').doc(userRecord.uid).set({
email: userRecord.email,
phoneNumber: userRecord.phoneNumber,
}).catch(console.error);
};

module.exports = {
authOnCreate: functions.auth.user().onCreate(createProfile),
};

Of course, it is not good to have all your code in the index.js, so this is not a perfect solution. I have written an article about splitting Cloud Functions before. Follow that.

Once this profile there in the Firestore, you can always use it to store more data about your user.

For the example, I used the uid as the doc-id of the document inside the Users collection. You can leave it blank which will give the document an auto-id. Or, you can simply use something else, like the phoneNumber or the email.

Make sure that you always return a promise from the auto-triggering Cloud Functions. Not doing so will result in unstable behavior where sometimes, Firebase will or will not create the document in Firestore.