Handling linking accounts in Firebase

I think the Firebase API changed a bit and firebase.auth().currentUser.link(savedCred); is now firebase.auth().currentUser.linkWithRedirect(provider). In my implementation I'm saving the initially selected provider to sessionStorage and use that with the above method in case account linking is required.

You can also do linkWithPopUp if that suits your needs better.


These are roughly the steps on how to handle auth/account-exists-with-different-credential: You will get that error if you are signing in to a new Facebook account that uses the email of another account that already exists. Let's say the existing account is a google account.

You will get that error in getRedirectResult().catch(function(error) {})

The error will also contain an email and credential field. You will need to save the credential (using the recommended sessionStorage). Check this post for more on that: Firebase Authentication Javascript: setCookie for pending Credential for redirect

You then call firebase.auth().fetchProvidersForEmail(error.email) to determine the providers that already exist for that email.

You will then sign in to one of those existing providers and assert that the email is the same as error.email. On success, you will load the pending credential from sessionStorage, re-initialize as described in the other post and link it to the currentUser:

firebase.auth().currentUser.linkWithCredential(savedCred);

You will now have both accounts linked. Keep in mind the existing provider could be a password type. In that case you don't need to save the credential, you just ask the user for the password and sign them in using the same email error.email. You can then call link directly with the error.credential.

BTW, I recommend firebaseui-web which takes care of all this for you: https://github.com/firebase/firebaseui-web