Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud. Firestore Security Rules are essential to secure your data. In this tutorial, we will learn how to manage Firestore Security Rules.
Firestore Security Rules are written in a custom, JSON-like language. These rules are used to determine who has read and write access to your Firestore database, how documents are structured and what indexes exist.
You can write Firestore Security Rules in the Firebase console. Here's an example of how a rule looks like:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
This rule simply denies all read and write operations.
You can update Firestore Security Rules from Firebase Console. Navigate to the "Database" section, select the "Rules" tab, and update your rules.
To test Firestore Security Rules, you can use the Firestore rules simulator in the Firebase console. This allows you to simulate read, write, and delete operations.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if request.auth.uid != null;
}
}
}
In this example, allow read: if true;
allows all users to read the data. allow write: if request.auth.uid != null;
allows only authenticated users to write the data.
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
}
}
In this example, allow read, write: if request.auth.uid == userId;
allows users to read and write only their own data.
In this tutorial, we learned what Firestore Security Rules are, how to write, update, and test these rules.
service cloud.firestore {
match /databases/{database}/documents {
match /documents/{docId} {
allow read, write: if request.auth.uid == resource.data.creator;
}
}
}
In this rule, only the creator of the document, whose user ID is stored in the creator
field, can read and write the document.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if request.auth.token.email_verified;
}
}
}
In this rule, allow read: if true;
allows anyone to read the documents, and allow write: if request.auth.token.email_verified;
allows only users with a verified email to write.