Search code examples
flutterfirebasedartgoogle-cloud-firestoregoogle-cloud-functions

How do we make sure "adding user details to 'user' collection on createUserWithEmailAndPassword success" is ATOMIC in Firebase (Flutter)


I am trying to create a user in "users" collection on Firestore, once Firebase createUserWithEmailAndPassword is successful. I want to make this atomic like deleting the created user(how). There are alternatives like Cloud Functions, but I want to do it without those.

This is my code

    try {
      UserCredential userCredential = await Auth()
          .createUserWithEmailAndPassword(email: email, password: password);
      await FirebaseFirestore.instance
          .collection("users")
          .doc(userCredential.user!.uid)
          .set({"name": name, "email": email, "password": password});
      _isRegistrationSuccess = true;
      onRegister?.call();
    } catch (e) {
      _isRegistrationSuccess = false;
    }

How do we make sure that the code in the try block is atomic, i.e. createUserWithEmailAndPassword rolls back if the next steps fail (all or none)? Please tell us how we implement this atomicity in dart code, if Firebase does not provide it out of the box.

Thanks


Solution

  • I am trying to create a user in the "users" collection on Firestore, once Firebase createUserWithEmailAndPassword is successful. I want to make this atomic like deleting the created user.

    Firebase doesn't support cross-product transactional operations. So there is no way you can perform two atomic operations, like creating a user with email and password in Firebase Authentication and adding a user in Firestore, in a single step, meaning either both operations succeed or both fail with an error.

    So, the best option is to nest both calls and always handle the errors. If the first operation fails, stop, and don't perform the second one, or if the second operation fails, roll back the first operation.

    A more convenient way of handling this situation would be to trigger a Cloud Function in response to the creation of a Firebase user account. I've seen that you don't want to use a Cloud Function, but in my opinion, it is the most convenient way in such cases and you will only need to handle a single operation on the client.