How to know if a user has just been created or already existed with google signin and firebase web 9?

Viewed 183

I had a problem when using firebase authentication for web version 9, when using Google sign-in, there is no apparent difference between a newly created user (sign-up) and user that has been created previously (log-in), both of them use the same code base:

import { getAuth, GoogleAuthProvider } from "firebase/auth"  

const auth = getAuth()  
const googleProvider = new GoogleAuthProvider()  

signInWithPopup(auth, googleProvider).then((result) => {
  const user = result.user
})  

I would want to differentiate between a new user or an already existing user, to make sure I ask new users for more info just after user creation.
I have found some solutions where you use firestore and check if a user is in the database, but I think there should be an easier and straight forward solution to this.
Other solutions I found on stackoverflow are for older version than version 9.

1 Answers

You can check if a user is new or not by using getAdditionalUserInfo like so:

import { getAuth, GoogleAuthProvider, getAdditionalUserInfo } from "firebase/auth"  

const auth = getAuth()  
const googleProvider = new GoogleAuthProvider()  

signInWithPopup(auth, googleProvider).then((result) => {
  const additionalUserInfo = getAdditionalUserInfo(result)
  // you can know if the user is new or not
  cons isNewUser = additionalUserInfo.isNewUser
  const user = result.user
}) 
Related