Common Security Rules Patterns in Firebase: Best Practices
Firebase security rules use
match and allow statements to control access to data. Common patterns include user-based access with request.auth.uid, role-based checks, and data validation to keep your database safe.Syntax
Firebase security rules use match blocks to specify paths in your database and allow statements to define what actions are permitted. The main actions are read and write. Conditions use request.auth to check user identity and resource.data to validate existing data.
firebase
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /collection/{docId} { allow read, write: if <condition>; } } }
Example
This example shows a common pattern where users can read and write only their own documents in a users collection. It uses request.auth.uid to check the user's ID matches the document ID.
firebase
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } }
Output
Users can only read and write their own user document; others are denied.
Common Pitfalls
One common mistake is allowing access without checking request.auth, which lets anyone read or write data. Another is not validating data structure, which can lead to bad or malicious data being saved.
Always check if the user is authenticated and validate data before allowing writes.
firebase
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /posts/{postId} { // Wrong: allows anyone to write allow write: if true; // Right: only authenticated users can write and data must have 'title' and 'content' allow write: if request.auth != null && request.resource.data.keys().hasAll(['title', 'content']); } } }
Quick Reference
- request.auth != null: User is signed in
- request.auth.uid == resource ID: User owns the data
- request.resource.data: Incoming data for validation
- resource.data: Existing data in database
- allow read, write: if condition;: Grants access based on condition
Key Takeaways
Always check
request.auth to ensure users are authenticated before granting access.Use
request.auth.uid to restrict access to user-specific data.Validate incoming data with
request.resource.data to prevent bad data.Avoid open rules like
allow write: if true; that expose your database.Structure rules with
match and allow for clear, maintainable security.