Setting Up and Configuring Firebase Realtime Database

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', 'john.doe@example.com');

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 ‘john.doe@example.com’.

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', 'new.email@example.com');

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 ‘new.email@example.com’.

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.



Contact Us