0

I am creating the authentication side of a web app using Firebase's Google Sign in and would like to see if the newUser.displayName is unique in the Firestore database. My current code doesn't work as I must create the user before accessing the displayName. If I create the user first and then check the displayName, that would cause problems as I would need to go back and delete the user if the condition is not met. Is there a way to access displayName before the user is created?

Signup.js

const handleGoogleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        try {
            const available = await usernameAvailability(newUser.user.displayName.replace(/\s/g, ""))
            const newUser = await signInWithGoogle(email, password);
            const { isNewUser } = getAdditionalUserInfo(newUser) 

            if (isNewUser) {
                await setDoc(doc(db, "users", newUser.user.uid), {
                    email: newUser.user.email,
                    uid: newUser.user.uid,
                    username: newUser.user.displayName.replace(/\s/g, ""),
                    usernameLowercase: newUser.user.displayName.toLowerCase(),
                });
            }
            navigate('/account');
        } catch (error) {
            setError(error.message);
            console.log(error.message);
        }
    }

AuthContext.js

const usernameAvailability = async (username) => {
        const q = query(collection(db, "users"), where("usernameLowercase", "==", username.toLowerCase()));
        const querySnapshot = await getDocs(q)
        console.log(querySnapshot.empty, 'querySnapshot.empty')
        if (querySnapshot.empty) {
            return true
        } else {
            throw new Error("Username already exists")
        }
    }
Elias Fizesan
  • 265
  • 1
  • 3
  • 18

1 Answers1

1

There is no way to query Firebase Authentication by the display name of the users, nor any way to a priori ensure that display names are unique. That is not their purpose, so I'd recommend not trying to make it do something it wasn't meant for.

The common approach to having unique user names is to store them in some cloud-hosted database (like Realtime Database or Firestore in Firebase, but others are also fine) and querying/claiming a name there before calling the Firebase API to create the user there.

This topic has been covered quite a few times before, so I recommend checking out these search results, such as:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807