Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

getting started with firebase realtime database on the web



During the past few decades, the relational database (RDBMS) SQL has been the primary model for database management. As an alternative model for database management, the non-relational "NoSQL" databases first used in 1998 by Carlo Strozzi has been gaining steam. 

The need for processing unstructured data and the need for faster processing gave rise to NoSQL. The non-relational system is quicker, uses an ad-hoc approach for organizing data, and processes large amounts of different kinds of data. For large, unstructured data, NoSQL databases are better compared with relational databases due to their speed and flexibility.

The Firebase Realtime Database is a NoSQL cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. Firebase Realtime Database is perfect when you build cross-platform apps. All clients share one Realtime Database instance and automatically receive updates with the newest data.

In this tutorial, we will be learning how to write, read, update, and delete data using Firebase Realtime Database on the web with JavaScript.

Creating a Firebase project

To get access to Firebase Realtime Database, you need to log in with your Google account and create a project on Firebase console to obtain your firebase initialization code. Click here to access this page.  

Watch the video below to learn how to create a Firebase project and initialize Firebase Realtime Database. 


If you have created your project and initialized the Realtime Database then your database will look like this


Adding Firebase to your web project

After creating your project, you should be able to obtain your Firebase initialization code

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->


<script>
 
// Your web app's Firebase configuration
 
var firebaseConfig = {
    apiKey
: "AIzaSyDHg0VrivE3C9A7jvzRu7lQgudLvcD_Fxk",
    authDomain
: "registration-cf470.firebaseapp.com",
    databaseURL
: "https://registration-cf470.firebaseio.com",
    projectId
: "registration-cf470",
    storageBucket
: "registration-cf470.appspot.com",
    messagingSenderId
: "921371494542",
    appId
: "1:921371494542:web:259209b868c843b08ea1df"
 
};
 
// Initialize Firebase
  firebase
.initializeApp(firebaseConfig);
</script>

There is a TODO section in the firebase initialization code that requires you to import  the Firebase Realtime Database SDK link shown below

<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-database.js"></script>

 If you added Firebase correctly to your web app, your web app should look something like this

<!DOCTYPE html>
<html>
  <head>
    <title>Firebase File Upload</title>

    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1"
    />
  </head>
  <body>
    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>

    <!-- TODO: Add SDKs for Firebase products that you want to use-->
    <script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-database.js"></script>

    <script>
      // Your web app's Firebase configuration
      var firebaseConfig = {
        apiKey: "AIzaSyDHg0VrivE3C9A7jvzRu7lQgudLvcD_Fxk",
        authDomain: "registration-cf470.firebaseapp.com",
        databaseURL: "https://registration-cf470.firebaseio.com",
        projectId: "registration-cf470",
        storageBucket: "registration-cf470.appspot.com",
        messagingSenderId: "921371494542",
        appId: "1:921371494542:web:259209b868c843b08ea1df",
      };
      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);
    </script>
  </body>
</html>

HTML

To demonstrate how to use Firebase Realtime Database, we will be creating a simple Registration form that will collect users information and store them in our database.

Name<br />
<input type="text" id="form-name" /><br />
Username<br />
<input type="text" id="form-username" /><br />
Gender<br />
<select id="form-gender">
  <option>Male</option>
  <option>Female</option>
  <option>Other</option> </select
><br />
<button>Register</button>


Name

Username

Gender



We will be collecting users name, username and their gender to be stored in the database.

Writing data to Firebase Realtime Database

To read or write data from the database, you need an instance of firebase.database.Reference. For basic write operations, you can use set() to write data to a specified reference, replacing any existing data at that path. For example, Let us trying writing our registration data to the database

const validateForm = () => {
  const name = document.querySelector("#form-name").value;
  const username = document.querySelector("#form-username").value;
  const gender = document.querySelector("#form-gender").value;

  if (name.trim() == "" || username.trim() == "" || gender == "") {
    alert("form not completely filled");
  } else {
    writeToDatabase(name, username, gender);
  }
};

const writeToDatabase = (name, username, gender) => {
  firebase
    .database()
    .ref("Registration/" + Date.now())
    .set({
      name: name,
      user: username,
      gender: gender,
    });
};

document.querySelector("#register").addEventListener("click", () => {
  validateForm();
});

First, what we did was to validate the form, then we invoked the writeToDatabase() method that takes the user information and stores them in our database. In our writeToDatabase() method, the ref("Registration/" + Date.now()) is the path where the user data will be written, so the parent node to the user data is a timestamp that acts a unique id. Now our database looks like this


Reading single node from database

To read data at a path and listen for changes, use the on() or once() methods of firebase.database.Reference to observe events. using the on() method will listen continuously for any changes in the database while the once() method accesses the database only once. The examples below show how to read first user details from the Firebase Realtime Database using the on() method

const readFromDatabaseOn = (id) => {
  firebase
    .database()
    .ref(id)
    .on("value"function (snapshot) {
      console.log(snapshot.val().name);
      console.log(snapshot.val().user);
      console.log(snapshot.val().gender);
    });
};

The once() method reads data only once, other changes made in the database does not reflect on the page unless otherwise refreshed.

const readFromDatabaseOnce = (id) => {
  firebase
    .database()
    .ref(id)
    .once("value"function (snapshot) {
      console.log(snapshot.val().name);
      console.log(snapshot.val().user);
      console.log(snapshot.val().gender);
    });
};

using the first user id  "1588079475872" as the id will print the following result for the on() and once() method


Reading multiple nodes from database

Using the forEach() method, you can read all the child nodes from a particular parent node. Below is an example that reads all users data in our database.

const readMultipleNodesFromDatabase = () => {
  firebase
    .database()
    .ref("Registration")
    .once("value"function (snapshot) {
      x = 1;
      snapshot.forEach(function (childSnapshot) {
        console.log("user " + x);
        console.log(childSnapshot.val().name);
        console.log(childSnapshot.val().user);
        console.log(childSnapshot.val().gender);
        console.log(" ");
        x++;
      });
    });
};

Running the method above will give you the result below retrieved from the database

both the on() and once() method can be used to read multiple nodes.

Updating on Firebase Realtime Database

To simultaneously write to specific children of a node without overwriting other child nodes, use the update() method. I prefer using the update() method instead of set() method due to the fact that the update() method does not overwrite the entire node. Let us add the ages of the first user in the example below.

const updateUserDetails = (id, age) => {
  firebase
    .database()
    .ref("Registration/" + id)
    .update({
      age: age,
    });
};

using the first user id "1588079475872" as the id  and 27 as age will print the following result


Deleting nodes from Firebase Realtime Database

The remove() method is used to delete nodes from the database. The example below removes the first users details from the database

const removeUserDetails = (id) => {
  firebase
    .database()
    .ref("Registration/" + id)
    .remove();
};

using the first user id "1588079475872", the first user details will be removed as shown below


The complete web app

Below is the complete app we built in this tutorial.

<!DOCTYPE html>
<html>
  <head>
    <title>Firebase Realtime Database</title>

    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1"
    />
  </head>
  <body>
    Name<br />
    <input type="text" id="form-name" /><br />
    Username<br />
    <input type="text" id="form-username" /><br />
    Gender<br />
    <select id="form-gender">
      <option>Male</option>
      <option>Female</option>
      <option>Other</option> </select
    ><br />
    <button id="register">Register</button>

    <!-- The core Firebase JS SDK is always required and must be listed first -->
    <script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>

    <!-- TODO: Add SDKs for Firebase products that you want to use-->
    <script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-database.js"></script>

    <script>
      // Your web app's Firebase configuration
      var firebaseConfig = {
        apiKey: "AIzaSyDHg0VrivE3C9A7jvzRu7lQgudLvcD_Fxk",
        authDomain: "registration-cf470.firebaseapp.com",
        databaseURL: "https://registration-cf470.firebaseio.com",
        projectId: "registration-cf470",
        storageBucket: "registration-cf470.appspot.com",
        messagingSenderId: "921371494542",
        appId: "1:921371494542:web:259209b868c843b08ea1df",
      };
      // Initialize Firebase
      firebase.initializeApp(firebaseConfig);
    </script>

    <script>
      const validateForm = () => {
        const name = document.querySelector("#form-name").value;
        const username = document.querySelector("#form-username").value;
        const gender = document.querySelector("#form-gender").value;

        if (name.trim() == "" || username.trim() == "" || gender == "") {
          alert("form not completely filled");
        } else {
          writeToDatabase(name, username, gender);
        }
      };

      const writeToDatabase = (name, username, gender) => {
        firebase
          .database()
          .ref("Registration/" + Date.now())
          .set({
            name: name,
            user: username,
            gender: gender,
          });
      };

      document.querySelector("#register").addEventListener("click", () => {
        validateForm();
      });

      const readFromDatabaseOn = (id) => {
        firebase
          .database()
          .ref(id)
          .on("value"function (snapshot) {
            console.log(snapshot.val().name);
            console.log(snapshot.val().user);
            console.log(snapshot.val().gender);
          });
      };

      const readFromDatabaseOnce = (id) => {
        firebase
          .database()
          .ref(id)
          .once("value"function (snapshot) {
            console.log(snapshot.val().name);
            console.log(snapshot.val().user);
            console.log(snapshot.val().gender);
          });
      };

      const readMultipleNodesFromDatabase = () => {
        firebase
          .database()
          .ref("Registration")
          .once("value"function (snapshot) {
            x = 0;
            snapshot.forEach(function (childSnapshot) {
              console.log("user " + x);
              console.log(childSnapshot.val().name);
              console.log(childSnapshot.val().user);
              console.log(childSnapshot.val().gender);
              console.log(
                childSnapshot.val().age == undefined
                  ? ""
                  : childSnapshot.val().age
              );
              console.log(" ");
              x++;
            });
          });
      };

      const updateUserDetails = (id, age) => {
        firebase
          .database()
          .ref("Registration/" + id)
          .update({
            age: age,
          });
      };

      const removeUserDetails = (id) => {
        firebase
          .database()
          .ref("Registration/" + id)
          .remove();
      };

    </script>
  </body>
</html>

SQL queries converted for Firebase Database

The YouTube video below converts some SQL queries for Firebase Database


conclusion

Firebase Realtime Database is very easy to use and it's good for folks who want to build server-less apps. Firebase has a complete solution that can help you build your apps from start to finish without configuring servers. over the coming weeks I will make more tutorials Firebase, ciao.