Step-by-step guide to using Firebase Realtime Database transactions for safe, concurrent data updates and secure app rules.

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 in Your Project
First, ensure that your Firebase project is set up. If you haven't, go to the Firebase Console and create a new project. Follow the setup instructions to add Firebase to your app (web, iOS, or Android). Once Firebase is added, ensure that the Realtime Database is enabled.
Step 2: Initialize Firebase in Your Application
For a web app, you typically initialize Firebase in your main JavaScript file. Make sure you replace the Firebase configuration with your own Firebase project settings.
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
Step 3: Structure Your Realtime Database
Decide on the structure of your Realtime Database. For example, let's assume you have a users node where each user has a name, age, and balance.
{
"users": {
"user1": {
"name": "John Doe",
"age": 30,
"balance": 100
},
// More users...
}
}
Step 4: Implement a Transaction
Transactions are useful when you need to ensure that the data has not been changed by another client before you modify it. Use transactions to modify data safely by applying a function to the current state of the data. For example, let's increment a user's balance:
import { ref, runTransaction } from "firebase/database";
function incrementUserBalance(userId, incrementValue) {
const userRef = ref(database, 'users/' + userId + '/balance');
runTransaction(userRef, (currentBalance) => {
if (currentBalance === null) {
return incrementValue; // Initial balance if it was null
}
return currentBalance + incrementValue;
}).then((transactionResult) => {
if (transactionResult.committed) {
console.log('Transaction committed successfully:', transactionResult.snapshot.val());
} else {
console.log('Transaction not committed.');
}
}).catch((error) => {
console.log('Transaction failed: ', error);
});
}
// Invocation Example:
incrementUserBalance("user1", 50);
Step 5: Handle Transaction Results
After invoking runTransaction, it returns a promise. Check if the transaction was committed or not using .committed. Handle errors with a .catch block to ensure any issues during the transaction are logged or resolved.
Step 6: Test the Transaction
Run your application and trigger the transaction to ensure that it is working as expected. Check the Realtime Database in the Firebase Console to see if the data has updated correctly.
Step 7: Review and Secure Your Database Rules
After setting up transactions, make sure to review and secure your database rules in the Firebase Console to prevent unauthorized access. Rules should validate data and authorize users according to your app's requirements.
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"users": {
"$user_id": {
".validate": "newData.child('balance').val() >= 0"
}
}
}
}
With these steps, you can successfully implement transactions in your Firebase Realtime Database to manage concurrent data updates efficiently and securely.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.