Match – Firestore Security Rules

Before we write any rules we need to define where in the database a rule applies to, that represents a path to your data in your database. In a brand new project in Firebase, you’ll notice that by default there is a match block that points to the root of your database.

this is a generic boilerplate code that puts you in the root of your database. Now there are three main types of matching patterns, single document match, collection match, or a hierarchy of collection and sub-collection match.

Single Document Match

Imagine you have a lot of users and each of them gets a unique uuid from Firebase authentication and you need to allow users to access only the data they own.

Here is how you can write a firestore rule to keep the data secure and accessible to the owner of it.

 match /users/{uid} {
    allow read, write: if uid == request.auth.uid

Here you define that every “uid (variable)” in the “users” collection is to be allowed to read and write if the “uid” that is the document ID matches the uid provided by the firebase auth in the request made.

In short, you’re matching the document ID with the UID of the requesting user to check if he is allowed to access the collection or not.

Remember : The rules on parent collection doesn’t apply to sub collections of it

If you had an items collection nested under the user’s collection the user match rule doesn’t apply for that as it’s isolated with its own security policies.

You might want to apply the same rules for all the collections under a parent collection and that’s where recursive wild card is used.

Collection Match

 match /users/{docId=**} {
    allow read, write;

In the above snippet if the user is allowed to read the user collection then it applies to all of its subcollections too. This way you don’t have to write a separate set of rules for all the collections under a parent collection.

If you want to define security rules to sub-collections then you can do that too.

match /users/{uid} {
   allow read, write: if uid == request.auth.uid
   match /users/{uid}/photos/{pid} {
     allow read, write;

in this case, you’re defining rules for “photos” collection which is under users (parent) collection.

Security is always excessive until it’s not enough

Hope this gave you an overview of using match in writing Firebase Firestore Security Rules.

Any issue? Comment down below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like