How to Set Security Rules for Firebase Realtime Database
To set security rules for Firebase Realtime Database, write rules in the
Firebase Console under the Rules tab using JSON syntax. These rules define who can read or write data at specific database paths, ensuring your data is protected.Syntax
Firebase Realtime Database security rules use JSON-like syntax to specify permissions. The main parts are:
- "rules": The root object containing all rules.
- Database paths: Define where rules apply, like
"/users/{userId}". - "read" and "write": Boolean expressions controlling access.
- Variables: Use curly braces
{}to capture dynamic path segments.
json
{
"rules": {
"path": {
"$variable": {
".read": "condition",
".write": "condition"
}
}
}
}Example
This example allows users to read and write only their own data under /users/{userId}. It uses auth.uid to check the signed-in user's ID matches the data path.
json
{
"rules": {
"users": {
"$userId": {
".read": "$userId === auth.uid",
".write": "$userId === auth.uid"
}
}
}
}Output
If a user is signed in with UID 'abc123', they can only read and write data at /users/abc123.
Common Pitfalls
Common mistakes when setting security rules include:
- Not requiring
auth != nullto ensure users are signed in. - Using overly broad rules like
"read": truethat expose all data publicly. - Forgetting to test rules in the Firebase Console simulator before deploying.
- Misusing variables or path segments causing unintended access.
json
{
"rules": {
"data": {
".read": true, // Wrong: allows anyone to read all data
".write": false
}
}
}
// Corrected version:
{
"rules": {
"data": {
".read": "auth != null",
".write": "auth != null"
}
}
}Quick Reference
Here is a quick summary of key rule components:
| Rule Part | Description | Example |
|---|---|---|
| rules | Root object for all rules | "rules": { ... } |
| path | Database location to apply rules | "users": { ... } |
| $variable | Dynamic path segment | "$userId": { ... } |
| read | Condition to allow reading data | ".read": "auth != null" |
| write | Condition to allow writing data | ".write": "$userId === auth.uid" |
| auth | Authentication info of user | auth.uid, auth.token |
| true / false | Allow or deny access | ".read": true |
Key Takeaways
Write security rules in JSON syntax under the Firebase Console Rules tab.
Use
auth.uid to restrict data access to authenticated users.Always test your rules with the Firebase simulator before deploying.
Avoid public read/write permissions unless intentional.
Use variables to create flexible, path-based access controls.