Firebase – addDoc() returns success even when no document was added

New to Firebase. I have a basic React form that takes a user’s email and sends it to Firestore using addDoc().

import { initializeApp } from "firebase/app";
import { getFirestore } from "@firebase/firestore"

const firebaseConfig = {
  ...
};
// Initialize Firebase
export const app = initializeApp(firebaseConfig);

export const db = getFirestore(app)
const emailsCollectionRef = collection(db, "emails");

const addEmail = async (data: { email: string; }) => {
        console.log("Sending data to firebase");
    try {    
        const result =  await addDoc(emailsCollectionRef, {email: data!.email});
        console.log("Document written with ID: ", result.id);

    } catch (e) {
        console.error("Error adding document: ", e);
      }
        
    }

When I pass the user’s input using addDoc() in a try catch I get this in the console

Sending data to firebase
Document written with ID:  YFPaCvSjeBssvUAtdqSh

Which is fine, but if I purposefully try to make it fail like for example changing the name of the collection in emailsCollectionRef e.g.

const emailsCollectionRef = collection(db, "NoSuchCollection");

and run the function again I get the same success message.

In the Firebase docs it says that addDoc()

Returns:

Promise<DocumentReference<T>>

A Promise resolved with a DocumentReference pointing to the newly created document after it has been written to the backend (Note that it won’t resolve while you’re offline).

and under DocumentReference it says

A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist.

If I want to check if the write was succesful I have to ignore DocumentReference and immediately after using addDoc() do a separate query to see if that ID actually exists.

My question is, is there a better way to check if the write was actually succesful since DocumentReference obviously cannot be trusted?

>Solution :

Collections are created automatically when you write the first document to is, so quite likely your addDoc call with the non-existing collection actually creates that collection.

If you want to prevent that, you can only allow writes to specific, known collections in your database’s security rules, which are enforced on the server. At that point, the promise returns by addDoc will also reject/fail.

Leave a Reply