Search code examples
javascriptgoogle-cloud-firestorefirebase-security

Error Missing or insufficient permissions in React app


  • I'm having a problem trying to access the firestore in my React App project
  • Specifically, I have a code to register a user with firebase authentication and after success will setDoc the user to firestore.
  • Successfully authenticated user registration but cannot setDoc to firestore, specific error "Uncaught (in promise) FirebaseError: Missing or insufficient permissions." Please help me to solve that problem.

This my signup with Firebase authentication

function signUp(email,password){
            createUserWithEmailAndPassword(auth,email,password);
            setDoc(doc(db,'users', email),{ 
                 savedShows:    []
             }) 
        }

and this's my cloud Firestore rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{email} {
      allow create: if request.auth != null && request.auth.token.email == email;
      allow read, write: if request.auth.token.email == email;
    }
  }
}

Solution

  • The createUserWithEmailAndPassword is an asynchronous call, so the call won't be done immediately.

    You need to either await for it to be done, or use then to only add to the database once it's done.

    So:

    createUserWithEmailAndPassword(auth,email,password).then((cred) => {
      setDoc(doc(db,'users', email), { 
        savedShows: []
      }) ;
    });
    

    Or (if you're in an async context):

    const cred = await createUserWithEmailAndPassword(auth,email,password);
    await setDoc(doc(db,'users', email), { 
      savedShows: []
    })