grayger
grayger

Reputation: 931

uid-already-exist error when creating a non-existing user

There is a firebase server-side(firebase functions) code which creates a user if given userId doesn't exist.

It usually works fine, but rarely fails.

function createUserIfNotExist(userId, userName) {
    admin.auth().getUser(userId).then(function (userRecord) {
        return userRecord;
    }).catch(function (error) {
        return admin.auth().createUser({
            uid: userId,
            displayName: userName,
        })
    })
}

When given userId doesn't exist, admin.auth().getUser() throws

{ code: 'auth/user-not-found', message: 'There is no user record corresponding to the provided identifier.' } 

So admin.auth().createUser() is called in catch clause. But it sometimes fails with following error

{ Error: The user with the provided uid already exists.
    at FirebaseAuthError.Error (native)
    at FirebaseAuthError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28)
    at new FirebaseAuthError (/user_code/node_modules/firebase-admin/lib/utils/error.js:104:23)
    at Function.FirebaseAuthError.fromServerError (/user_code/node_modules/firebase-admin/lib/utils/error.js:128:16)
    at /user_code/node_modules/firebase-admin/lib/auth/auth-api-request.js:399:45
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
  errorInfo: 
   { code: 'auth/uid-already-exists',
     message: 'The user with the provided uid already exists.' } }    

Is it firebase bug or something is wrong in my code?

Upvotes: 1

Views: 1529

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38299

There don't appear to be a lot of other documented reasons besides auth/internal-error why the call to getUser() would fail, but it would be safer to explicitly check for auth/user-not-found before requesting creation of a new user:

function createUserIfNotExist(userId, userName) {
    admin.auth().getUser(userId).then(function (userRecord) {
        return userRecord;
    }).catch(function (error) {
        if (error.code === 'auth/user-not-found') {
            return admin.auth().createUser({
                uid: userId,
                displayName: userName,
            });
        } else {
            console.error("Error getting user data:", error);
        }
    })
}

Upvotes: 2

Related Questions