Setting Up and Configuring Firebase Realtime Database
Last Updated :
27 May, 2024
Firebase Realtime Database is a cloud-hosted NoSQL database that allows us to store and sync data between our users in real-time. It is a powerful tool for building applications that require live updates, such as chat apps, collaborative tools, and real-time analytics.
In this article, we will learn about the Firebase Realtime Database, the process of Setting Up Firebase Realtime Database and configuring the Firebase Realtime Database with detailed examples and outputs.
What is Firebase Realtime Database?
- Firebase Realtime Database is a NoSQL cloud database that allows developers to store and sync data in real-time across all clients. Data is stored as JSON and synchronized in real-time to every connected client.
- This makes it perfect for applications that require live updates, such as chat apps, collaborative tools and real-time analytics.
Setting Up Firebase Realtime Database
Step 1: Create a Firebase Project
- Go to Firebase Console: Navigate to the Firebase Console.
- Add a New Project: Click on "Add project" and follow the setup instructions. Enter our project name, configure Google Analytics (if needed), and click "Create Project."
Step 2: Add Firebase to Your App
Firebase provides detailed guides for adding Firebase to various platforms. Here’s how to add Firebase to a web project:
Register Your App:
- In the Firebase console, click on the Web icon (</>) to register your web app.
- Type a name for your app and then click on "Register app."
Add Firebase SDK:
Firebase will provide us with a code snippet. Copy this and include it in your HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Firebase Realtime Database Example</title>
</head>
<body>
<h1>Firebase Realtime Database Example</h1>
<input type="text" id="messageInput" placeholder="Enter message">
<button onclick="sendMessage()">Send Message</button>
<ul id="messageList"></ul>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-database.js"></script>
<script>
const firebaseConfig = { apiKey: "AIzaSyDmaZAcK7xwQTAsQJxaGnG56oB8RIJDMnc", authDomain: "samplep-d6b68.firebaseapp.com", projectId: "samplep-d6b68", storageBucket: "samplep-d6b68.appspot.com", messagingSenderId: "398502093281", appId: "1:398502093281:web:5d685b0733d4d6d66472a0", measurementId: "G-9E6K9YD8D1"};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
function sendMessage() {
const messageInput = document.getElementById("messageInput");
const message = messageInput.value;
if (message.trim() === "") {
alert("Please enter a message.");
return;
}
database.ref("messages").push({
message: message,
timestamp: firebase.database.ServerValue.TIMESTAMP
});
messageInput.value = "";
}
database.ref("messages").on("child_added", (snapshot) => {
const message = snapshot.val().message;
const timestamp = new Date(snapshot.val().timestamp).toLocaleString();
const messageElement = document.createElement("li");
messageElement.innerText = `${timestamp}: ${message}`;
const messageList = document.getElementById("messageList");
messageList.appendChild(messageElement);
});
</script>
</body>
</html>
Output:

Step 3: Enable Realtime Database
Go to Realtime Database:
- Go to the Firebase Console and select "Realtime Database" from the menu on the left.
Create a Database:
- Click on "Create Database."
- Select your database location and choose a security rule. For development purposes, you can start in "test mode" which allows read and write access to our database.
Security Rules:
- Initially, we might want to set our rules to allow read and write access to anyone for testing purposes.
- Make sure to update these rules before deploying our app to production.
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Configuring Firebase Realtime Database
Writing Data
To write data to Firebase Realtime Database, use the set method. Here’s an example of writing user data to the database:
function writeUserData(userId, name, email) {
firebase.database().ref('users/' + userId).set({
username: name,
email: email
});
}
// Example usage
writeUserData('1', 'John Doe', '[email protected]');
Explanation: This function writeUserData
writes user data (name and email) to the Firebase Realtime Database under the users
node with the specified userId
. The example usage demonstrates how to write data for a user with ID '1', name 'John Doe', and email '[email protected]'.
Reading Data
To read data from Firebase Realtime Database, use the once method to read data once or the on method to listen for changes in the data.
Reading Data Once:
function readUserData(userId) {
const userRef = firebase.database().ref('users/' + userId);
userRef.once('value').then((snapshot) => {
const data = snapshot.val();
console.log(data);
});
}
// Example usage
readUserData('1');
Explanation: This function readUserData
reads user data from the Firebase Realtime Database for a specific userId
. It retrieves the data once using once('value')
and logs it to the console. The example usage demonstrates how to read data for a user with ID '1'.
Listening for Data Changes:
function listenForUserData(userId) {
const userRef = firebase.database().ref('users/' + userId);
userRef.on('value', (snapshot) => {
const data = snapshot.val();
console.log(data);
});
}
// Example usage
listenForUserData('1');
Explanation: This function listenForUserData
sets up a listener for changes to user data in the Firebase Realtime Database for a specific userId
. It uses on('value')
to listen for any changes and logs the updated data to the console. The example usage demonstrates how to listen for changes to data for a user with ID '1'.
Updating Data
To update specific fields in your data without overwriting the entire node, use the update method:
function updateUserData(userId, email) {
const updates = {};
updates['/users/' + userId + '/email'] = email;
firebase.database().ref().update(updates);
}
// Example usage
updateUserData('1', '[email protected]');
Explanation: This updateUserData
function updates the email field of a user in the Firebase Realtime Database for a specified userId
. It constructs an updates object with the new email value and uses update()
to apply the changes to the database. The example usage demonstrates how to update the email for a user with ID '1' to '[email protected]'.
Deleting Data
To delete data from Firebase Realtime Database, use the remove method:
function deleteUser(userId) {
firebase.database().ref('users/' + userId).remove()
.then(() => {
console.log('User removed successfully.');
})
.catch((error) => {
console.error('Error removing user:', error);
});
}
// Example usage
deleteUser('1');
Explanation: This `deleteUser` function removes a user from the Firebase Realtime Database for a specified `userId`. It uses `remove()` to delete the user node and handles success and error cases with `then()` and `catch()` respectively. The example usage demonstrates how to delete a user with ID '1'.
Example: Simple Realtime Task List
Let’s create a simple task list application to demonstrate Firebase Realtime Database in action.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Realtime Task List</title>
</head>
<body>
<h1>Realtime Task List</h1>
<div id="task-list"></div>
<input type="text" id="task-input" placeholder="Enter a task">
<button onclick="addTask()">Add Task</button>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.4/firebase-database.js"></script>
<script>
const firebaseConfig = { apiKey: "AIzaSyDmaZAcK7xwQTAsQJxaGnG56oB8RIJDMnc", authDomain: "samplep-d6b68.firebaseapp.com", projectId: "samplep-d6b68", storageBucket: "samplep-d6b68.appspot.com", messagingSenderId: "398502093281", appId: "1:398502093281:web:5d685b0733d4d6d66472a0", measurementId: "G-9E6K9YD8D1"};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
const taskList = document.getElementById('task-list');
function addTask() {
const task = document.getElementById('task-input').value;
const newTaskKey = firebase.database().ref().child('tasks').push().key;
const taskData = {
key: newTaskKey,
task: task
};
const updates = {};
updates['/tasks/' + newTaskKey] = taskData;
firebase.database().ref().update(updates);
document.getElementById('task-input').value = '';
}
database.ref('tasks/').on('value', (snapshot) => {
taskList.innerHTML = '';
snapshot.forEach((childSnapshot) => {
const childData = childSnapshot.val();
const taskElement = document.createElement('p');
taskElement.textContent = childData.task;
taskList.appendChild(taskElement);
});
});
</script>
</body>
</html>
Output:

Explanation:
- HTML Structure: The HTML file includes input fields for typing tasks and a button to add them to the task list.
- Initialize Firebase: Firebase is initialized with the configuration details.
- Adding Tasks: The addTask function pushes tasks to the tasks node in the database.
- Listening for Tasks: The on method listens for changes in the tasks node and updates the task list in real time.
Conclusion
Overall, Firebase Realtime Database is a powerful tool for building applications that require real-time data synchronization. Whether you're building a chat app, collaborative tool, or real-time analytics dashboard, Firebase Realtime Database can help you to achieve your goals with minimal setup and effort.
Similar Reads
Firebase Realtime Database: Reading and Writing Data
Firebase Realtime Database, a cloud-hosted NoSQL database developed by Google, provides a robust solution for achieving seamless real-time data updates across connected clients. In this article, We will learn about the Firebase Realtime Database, How to Setting Up the Firebase Realtime Database, wri
7 min read
Firebase Realtime Database
Firebase Realtime Database is a powerful NoSQL cloud database that enables real-time data storage and synchronization across all clients. It's particularly suited for applications requiring live updates, such as chat apps and collaborative tools. By following the setup instructions and using the pro
7 min read
Realtime Database vs Firestore
Realtime Database:Firebase is a real-time database that is a JSON datastore.It's totally unstructured which is a blessing and a curse.It is the Firebaseâs first and original cloud-based database.This real-time database demonstrates very low latency.Firebase Database Rules is the only security option
3 min read
A/B Testing with Firebase Remote Config
Firebase Remote Config and A/B Testing are powerful tools that allow developers to enhance and optimize their apps performance and user experience. Firebase Remote Config enables us to modify the behavior and appearance of your app in real time without requiring users to download updates. In this ar
5 min read
How to get current date and time in firebase using ReactJS ?
This article provides a detailed walkthrough on obtaining the current date and time in a Firebase environment using ReactJS. Readers will gain insights into the implementation process, enabling date and time functionalities into their React projects powered by Firebase. Prerequisites:Node JS or NPMR
2 min read
Integrating Real-time Database and Authentication using Next JS and Firebase
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. In this article, we will learn how to integrate Firebase's real-time database
5 min read
How to Use Firebase Firestore as a Realtime Database in Android?
Firebase Firestore is the backend database that is used to add, read, update and delete data from Android. But in Firebase Firestore there is a separate method that is used to read data from Firebase Firestore in Realtime Database. In this article, we will read data from Firebase Firestore in Realti
6 min read
How to Retrieve PDF File From Firebase Realtime Database in Android?
When we are creating an Android app then instead of inserting a pdf manually we want to fetch the pdf using the internet from Firebase. Firebase Realtime Database is the backend service that is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It
8 min read
What would be the AWS equivalent to Firebase Realtime Database?
Cloud-based applications are gaining a lot of popularity in modern development, this means that developers have to move to the cloud providers for the backend services so that they can make sure that development is simple and fast. especially when it comes to the real-time data synchronization. Intr
8 min read
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading
8 min read