Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Firebase transaction to create user collection and Authenticated user?

I am authenticating users through Firebase Authentication and saving some extra metadata about user in users collection. I want to perform create operation the way that either both can get created or failed. I don't want to create at only one place.

I have below code so far. It is very dangerous because it is highly possible that only one can get created and one can get failed:

  const newUser = req.body;
  try {
    const user = await admin.auth().createUser(newUser);

    /* Add user to users collection */
    usersRef.doc(user.uid).set({
      type: 'user',
      notification: '',
      bio: ''
    });

    res.status(201).json(response(user.uid, ''));
  } catch (err) {
    res.status(400).json(response(null, 'Something went wrong! Please try again.'));
  }

I am fairly new to Firebase. I've very limited knowledge on the subject. I would really appreciate if anyone can redirect me to right direction. Thanks in advance!

like image 269
Kalpesh Patel Avatar asked Nov 18 '25 02:11

Kalpesh Patel


1 Answers

Personally, I would not classify this as a "highly possible" error. In practice, the only thing you're worrying about failing is the document creation, and for node.js code, that's only going to fail if you exceed some Firestore limitation, which is "extremely highly unlikely to occur" unless you're processing a LOT of new users whose UIDs happen to hit a single Firestore internal shard above its internal threshold (see limits). UIDs are pretty random and should distribute very broadly, so this shouldn't really be a concern. It might also fail if your server lacks internet access, but what really are the chances of it losing connectivity if it just previously completed a user creation?

Since you only have two operations here, it seems like you could simply check to see if the document didn't set() (and be sure to await the returned promise, which is missing right now). And if that fails, just delete the user and return an error to the client. And if you're worried about the user delete failing as well, I think you might be over-engineering this particular bit of code. You can always write code later that periodically checks user accounts to see if they don't have matching Firestore documents, and delete them.

You can make this a lot easier also by using Cloud Functions to automatically create the document after the user account is created. And if you mark that function as "retry", if the document creation fails, it will retry the document for several days until it works.

like image 176
Doug Stevenson Avatar answered Nov 19 '25 21:11

Doug Stevenson