How to Set Rules for Subcollection in Firebase Security Rules
To set rules for a
subcollection in Firebase, define the path in your security rules using nested match statements or a full path pattern like match /collection/{docId}/subcollection/{subDocId}. This lets you control read and write access specifically for documents inside the subcollection.Syntax
Firebase security rules use match blocks to specify paths. For subcollections, you include the parent document and then the subcollection name with wildcards for document IDs.
match /collection/{docId}/subcollection/{subDocId}: Targets documents inside a subcollection.allow read, write: if condition;: Defines access permissions based on conditions.
firebase
service cloud.firestore {
match /databases/{database}/documents {
match /collection/{docId}/subcollection/{subDocId} {
allow read, write: if <condition>;
}
}
}Example
This example shows rules that allow only authenticated users to read and write documents in a subcollection called comments inside a posts collection.
firebase
service cloud.firestore {
match /databases/{database}/documents {
match /posts/{postId}/comments/{commentId} {
allow read, write: if request.auth != null;
}
}
}Output
When deployed, only signed-in users can read or write documents in the 'comments' subcollection under any 'posts' document.
Common Pitfalls
Common mistakes include:
- Forgetting to include the full path to the subcollection, which causes rules to not apply.
- Using
match /collection/{docId}only, which does not cover subcollections. - Not using wildcards for document IDs, making rules too restrictive or invalid.
Always specify the full path with wildcards for both parent and subcollection documents.
firebase
service cloud.firestore {
match /databases/{database}/documents {
// Wrong: Does not cover subcollection
match /posts/{postId} {
allow read, write: if request.auth != null;
}
// Right: Covers subcollection 'comments'
match /posts/{postId}/comments/{commentId} {
allow read, write: if request.auth != null;
}
}
}Quick Reference
| Rule Part | Description | Example |
|---|---|---|
| /collection/{docId} | Matches documents in a collection | /posts/{postId} |
| /collection/{docId}/subcollection/{subDocId} | Matches documents in a subcollection | /posts/{postId}/comments/{commentId} |
| allow read, write: if condition; | Sets access permissions based on condition | allow read, write: if request.auth != null; |
| request.auth != null | Checks if user is signed in | if request.auth != null |
Key Takeaways
Always specify the full path including subcollection in your Firebase security rules.
Use wildcards like {docId} and {subDocId} to match document IDs dynamically.
Set conditions like 'request.auth != null' to control access based on user authentication.
Rules for parent collections do not automatically apply to subcollections.
Test your rules in Firebase console to ensure they work as expected.