← Back to blog
Firebase Security Rules: A Practical Guide
Engineering Team·
Firebase Security Rules are the gatekeepers of your data. Get them wrong and your database is exposed. Get them right and your app is secure by default.
The Principle of Least Privilege
Start by denying all access, then grant only what's needed:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Deny all by default
match /{document=**} {
allow read, write: if false;
}
// Grant access to specific collections
match /users/{userId} {
allow read, write: if request.auth != null
&& request.auth.uid == userId;
}
}
}
Testing Your Rules
Never deploy rules without testing. Use the Firebase Emulator Suite:
firebase emulators:start --only firestore,auth
Then test with the Firestore rules playground or automated integration tests.
Common Patterns
Authenticated access:
allow read: if request.auth != null;
Owner-only write:
allow write: if resource.data.userId == request.auth.uid;
Role-based access:
allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin';