Learn to secure your Firebase Realtime Database with our step-by-step guide on rules configuration, authentication, role-based access, data validation, and safe deployment.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up Firebase Project
Begin by creating a Firebase project in the Firebase Console. Navigate to Firebase Console, click on "Add project", follow the setup process, and configure Google Analytics if necessary. Make sure to choose the Realtime Database in the setup options.
Step 2: Access Firestore Database
Once your project is set up, proceed to the project overview and locate the Realtime Database section in the left-hand menu. Click on it to start configuring your database.
Step 3: Start in Test Mode (Optional)
You may start in test mode if you're just experimenting. Choose "Start in test mode" during the initial Realtime Database setup. This allows anyone with the database link to read and write data. However, this is not secure for production.
Step 4: Change Database Rules
Navigate to the "Rules" tab under Realtime Database. Here, you'll find a JSON file that governs access control rules. A basic rule just for reading and writing data looks like:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
This rule allows access only to authenticated users, ensuring unauthorized users cannot read or write data.
Step 5: Implement Role-Based Access Control
Define rules for specific user roles by structuring the JSON rules. For instance, store user roles in the database and write rules accordingly. Example:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
},
"adminContent": {
".read": "root.child('users/' + auth.uid + '/role').val() === 'admin'",
".write": "root.child('users/' + auth.uid + '/role').val() === 'admin'"
}
}
}
Step 6: Apply Data Validation
Ensure data integrity by adding validation rules. For example, if you're storing age, ensure it is a number:
{
"rules": {
...
"profiles": {
"$uid": {
".validate": "newData.child('age').isNumber() && newData.child('age').val() > 0"
}
}
}
}
Step 7: Test Your Rules
Firebase provides a simulator to test these rules. Click on the "Rules Playground" at the top-right of the Rules page, and simulate read/write requests to check if your rules work as expected.
Step 8: Deploy to Production with Caution
After testing, ensure your rule modifications won’t impact currently live applications. Export the rules as a .json file and deploy with caution. Use Firebase CLI for controlled deployments:
firebase deploy --only database
Secure your database with properly configured rules to prevent unauthorized access and maintain data integrity. Follow best practices by periodically reviewing and updating these rules.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.