Search code examples
javascriptfirebasegoogle-cloud-firestorefirebase-security

Firestore rules | Allow to get docs only if doc ids is provided


Im getting my documents based on a list of ids.

db.collection("fruits").where(db.FieldPath.documentId(), "in", fruitIds).get()

How should I write my security rules to allow the above call and to deny the below call

db.collection("fruits").get()

Solution

  • It's not possible exactly as you require. What you can do is set your rules like this:

    match /fruits/{id} {
      allow get: true;
      allow list: false;
    }
    

    This allows clients to get a document if they know the ID, but make it impossible to query documents in bulk.

    You will have to then code your client app request each document individually with a DocumentReference get() (instead of a Query with a where clause). The performance hit for this is negligible (no, there is not any noticeable performance gain for using an "in" query the way that you show here - and you are limited to 10 documents per batch anyway).