How to connect to Google Firebase Realtime database from your javascript project?

If you are looking to connect to a database on the cloud and you don’t want to spend any money in the initial stage , Google Firebase is an excellent choice.It has a generous free limit to get started.

Also you don’t need a server to connect to their database.

They provide SDKs (Software Development Kit) to connect.

You can connect to database from your javascript code!

They provide two database options:

  • Google Cloud Firestore
  • Google Firebase Realtime Database

Firestore is the latest and preferred over Realtime Database. Both are NoSQL databases.

But I had connection time out issues while using Firestore for one of my projects , so I switched over to Realtime Database.

Here is the algorithm to connect to Realtime Database.

STEP1: Create a new firebase project.

Create a new firebase project by logging into https://console.firebase.google.com with your google account credentials.

This is straightforward , just give a name and skip Google analytics if don’t need it when prompted for. A new project will get created for you.

STEP2: Create a new Realtime Database:

Navigate to Realtime Database in firebase console and click on Create Database.

Select “Test” Mode when prompted for defining security rules . Locked mode will deny read and writes to your database and you need to explicitly configure security rules. This should be used in production. But to test from your local you can choose test mode. It allows reads and writes for 30 days by default to anyone who knows your database details.

That’s it , a database got created!

STEP3: Configure database in your local javascript project.

To configure the database just created in your local , you need to get the configuration details from “Project Settings”:

Choose web from “Your apps” section , as we are going to connect from a javascript web project (</>)

You will be then prompted to register your app .

Give it a name.

Once you register , you will be shown the configuration details.

Just copy it to your javascript code:

You also need to include firebase database SDK which is not included in the above configuration:

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

I created a html file and included the code as below(the configuration values are removed, replace with your own):

<html>


<head>

</head>


<body>


<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.1.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 src="https://www.gstatic.com/firebasejs/8.1.1/firebase-database.js"></script>

<script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  
  
  	  
</script>




</body>

</html>

That’s it your connection logic is ready.

Now you can add data to your database.

Here is a write script which writes a JSON to a collection named “test”(it creates a new collection if it doesn’t already exist).

  let id = "123";
  
  let data = {};
  
  data["message"] = "Hello Google Firebase";
  
    firebase.database().ref('test/'+id).set(data,function(error) {
                if (error) {
                  // The write failed...

                  console.log({error});
                } else {

                                       
                    alert("success");
                  // Data saved successfully!
                }
              });
			  

Here is the full code:

<html>


<head>

</head>


<body>


<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.1.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 src="https://www.gstatic.com/firebasejs/8.1.1/firebase-database.js"></script>

<script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  
  
  let id = "123";
  
  let data = {};
  
  data["message"] = "Hello Google Firebase";
  
    firebase.database().ref('test/'+id).set(data,function(error) {
                if (error) {
                  // The write failed...

                  console.log({error});
                } else {

                                       
                    alert("success");
                  // Data saved successfully!
                }
              });
			  
			  
			  
</script>




</body>

</html>

I loaded the html file and the javascript got executed!

I went to firebase database console and saw that the data got inserted!

That’s it!

Git url for the above code:

https://github.com/vijaysrj/firebasedatabaseexample

Comments

2 responses to “How to connect to Google Firebase Realtime database from your javascript project?”

  1. Venkatachalam Ravi Avatar
    Venkatachalam Ravi

    Thank you for this tutorial. Very simple and direct.
    In other videos, we were told that the version number given in sdk code in config, should match the version in the .js files we should include.
    Though the present version I got online is 9.1.0, when I used your version .js files , it worked.

    1. Vijay SRJ Avatar
      Vijay SRJ

      Thank you very much for leaving feedback 😀

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading