
Firebase Authentication - Create User on Signup
5 min read
We want to create a user record in our database on signup. This database may be Firestore, but the patterns here work with any database you want to use.
So, I'm going to skip the singup
, and assume there are situations where the use didn't get their record created. We want to check if the record exists, even if this is not their first login. That being said, you could use this:
const credential = await signInWithPopup(this.auth, provider);
const additionalInfo = getAdditionalUserInfo(credential);
if (additionalInfo?.isNewUser) {
// create user here
}
But for most use cases, you want to be sure the user document gets created after the first login... just in case.
Method 1
Assume auth
is your Auth provider, and db
is Firestore. The database, however, could be any database.
const unsubscribe = onAuthStateChanged(auth, (user) => {
if (user) {
// check for record in Firestore or any database
const userSnap = await getDoc(doc(db, 'users', user.uid));
const userDoc = userSnap.exists() ? userSnap.data() : null;
if (!userDoc) {
// create user here
}
// set user state
}
}
- React - This should be placed inside a hook inside the useEffect. The user hook sets the state.
- Svelte - This should be placed inside a store. The writable value is the user.
- Angular - This should be placed inside of a service. A shared user value should be set.
- Vue - This should be placed inside as store. The state object will hold the user.
Note: - Remember to return the onAuthStateChanged
in stores and hooks (or even signals), or use onDestroy
in any other use case in order to unsubscribe to prevent memory leaks.
There are plenty of packages that do this for you, but most of them are overkill. Learn the patterns and you will excel!
Method 2
The other method, which ensures user creation, is to create a Cloud Function Trigger.
exports.yourTriggerName = functions.auth.user().onCreate((user) => {
const newUser = {
displayName: user.displayName,
email: user.email,
...
};
let db = admin.firestore();
db.collection('users', user.uid).add(newUser);
// save to Firestore or any database
...
});
Your data may be different, but this is the general pattern. There is also a onDelete()
trigger, but you need to make sure you don't have other user information tied to a user record (likes, posts, etc). In most cases, a soft-delete may be what you really want. In that case you just disable the user, or don't fetch documents that may have a delete field.
Good luck!
J