There are generally two ways to go about this - immediately in your signUp
code or via an auth trigger in Firebase Functions.
In Your Signup Code
You can create a document immediately after your async signUp
function:
async function signUp(email, password) {
// This function returns a credential which gives you the user's uid
// which you could then use to create your document
const credential = await createUserWithEmailAndPassword(auth, email, password);
const uid = credential.user.uid
// Create a new document using the uid as the document id
// or however else you want to use this
const ref = firebase.auth().collection("users").doc(uid)
await ref.set({
email,
uid
})
}
The good side of this is that you immediately create the document so you know it's there when your signUp
function returns. The down side is that you have to loosen some security rules to allow users to create documents on this collection from the client. There are plenty of ways to keep it secure, but just be aware of this.
With Cloud Functions
Your signUp
code creates a new auth record in Firebase, and Firebase has Authentication trigger functions that can fire when a new auth record is created or deleted.
exports.createUserDoc = functions.auth.user().onCreate((user) => {
// Your new auth record will have the uid and email on it because
// you used email as the way to create the auth record
return admin.firestore().collection("users").doc(user.uid).set({
email: user.email,
uid: user.uid
})
});
This is a secure way to handle things and doesn't require you to open up any security rules. But the drawback is that trigger functions are not guaranteed to fire immediately. They usually fire in a few seconds, but I've seen it take 30-60 seconds. So if your client-side code needs the document immediately on account creation, this is not a viable option.