How to Use resource.data in Firebase Security Rules
In Firebase security rules,
resource.data refers to the current data stored in a document before any changes. You use resource.data to check or validate existing document fields when reading or updating data.Syntax
The resource.data object represents the existing document's data in Firebase security rules. You can access fields using dot notation like resource.data.fieldName. It is commonly used in read and update rules to check current values.
firebase
allow update: if resource.data.owner == request.auth.uid;Example
This example shows a rule that allows a user to update a document only if they are the owner recorded in the existing document data.
firebase
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /posts/{postId} { allow update: if resource.data.owner == request.auth.uid; allow read: if true; } } }
Output
If the authenticated user ID matches the 'owner' field in the existing document, the update is allowed; otherwise, it is denied.
Common Pitfalls
- Using
request.resource.datainstead ofresource.datawhen you want to check existing data.request.resource.datais the new data being written. - Trying to use
resource.dataincreaterules where the document does not exist yet. - Not handling null or missing fields in
resource.data, which can cause errors.
firebase
allow create: if resource.data.owner == request.auth.uid; // Wrong: resource.data is null on create allow create: if request.resource.data.owner == request.auth.uid; // Correct
Quick Reference
| Term | Description |
|---|---|
| resource.data | Current data in the document before the request |
| request.resource.data | New data being written in the request |
| request.auth.uid | User ID of the authenticated user making the request |
| allow read | Rule to allow reading the document |
| allow update | Rule to allow updating the document |
Key Takeaways
Use resource.data to access existing document data in read and update rules.
Do not use resource.data in create rules because the document does not exist yet.
Use request.resource.data to access new data being written in create or update requests.
Always check for null or missing fields in resource.data to avoid errors.
resource.data helps enforce security by validating current document state before changes.