Home > Software design >  Firebase how to createUserWithEmailAndPassword and a user record at the same time?
Firebase how to createUserWithEmailAndPassword and a user record at the same time?

Time:11-23

Using Firebase, I'd like to do the following:

  1. Create a new user using FirebaseAuth (using createUserWithEmailAndPassword)
  2. Create a record for this new user in FireStore, where the document ID = user ID (adding fields such as name, role, gender etc.)

The problem is that once createUserWithEmailAndPassword is successful, an authStateChanges is triggered, and It's impossible to create the user record now...

How can I achieve this rather basic flow using Firebase's API?
Can I only achieve that using the Firebase Admin SDK?

CodePudding user response:

The problem is that once createUserWithEmailAndPassword is successful, an authStateChanges is triggered, and It's impossible to create the user record now...

Generally you would unsubscribe from the observer if you want to run some actions after registration like this:

const unsub = onAuthStateChanged(...);

const register = async () => {
  unsub(); // observer will not trigger on state changes
  // create user 
  // add document to Firestore
}

Alternatively, you can use Firebase Authentication Triggers to create document for user using Cloud Functions.

  • Related