Firebase Auth with Facebook fails if the account already exists and is associated with a Google Auth

Viewed 389

I'm implemented a simple app containing 2 buttons : 1 to login through Google and the other through Facebook.

Both authentication methods works individually but things gets more complicated when:

  • the user has a gmail address and 1st authenticate using the Google Login service
  • then, he comes back and tries to login using the Facebook Login service.

Here's comes the error code auth/account-exists-with-different-credential that has already been referenced here in stackoverflow Firebase JS API auth - account-exists-with-different-credential

The problem is that the errorobject I get doesn't contain a credential property name (nor an email property name btw) in the little app I've built.

Excerpt of loginWithFacebook.js in the App

export async function loginWithFacebook() {
    signInWithPopup(auth, new FacebookAuthProvider())
        .then((result) => {
            const user = result.user;
            console.log(user);
        })
        .catch(function (error) {
            if (error.code === 'auth/account-exists-with-different-credential') {
                console.log(error.credential); // undefined
                console.log(error.email); // undefined
            }
        });
}

link to the testing app

1 Answers

I had the same issue and I was able to overcome it by looking into the customData property of the returned error. Probably this different behavior has to do with the specific version of Firebase. Mine is firebase@9.6.9.

So, try to see if this works:

export async function loginWithFacebook() {
signInWithPopup(auth, new FacebookAuthProvider())
    .then((result) => {
        const user = result.user;
        console.log(user);
    })
    .catch(function (error) {
        if (error.code === 'auth/account-exists-with-different-credential') {
            console.log(FacebookAuthProvider.credentialFromError(error));
            console.log(error.customData.email);
        }
    });

}

Related