Firestore Security Rules are an essential part of Firebase that help you control access to your Firestore database. They determine who can read, write, or update data in your collections and documents. Proper rules ensure that your users’ data remains secure while enabling your app to function correctly.
Without security rules, anyone with your database URL could potentially read or modify your data. Rules allow you to enforce:
Firestore rules are defined in a firestore.rules file in your project. The basic syntax looks
like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false; // deny all access
}
}
}
This default rule denies access to everyone. You can then customize it for your app’s needs.
To allow only authenticated users to read and write data:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
In this example, a user can only access their own document. request.auth.uid ensures users
cannot
access other users’ data.
If you want to allow admins to manage all data while regular users can only read:
match /posts/{postId} {
allow read: if true; // everyone can read
allow write: if request.auth.token.admin == true;
}
Here, you can set a custom claim called admin for specific users. Only those users can write.
get() and exists() functions to validate related documents.Firestore Security Rules are critical for protecting your database and ensuring only authorized users can access or modify data. Properly designed rules, combined with authentication, make your app both functional and secure.