Firebase on the Web

I’m recently studying Firebase (I know it’s a bit late ever since Google announced new stuff), and I’m here to share what I’ve just learned (anyway).

What is Firebase?

Firebase is a Backend-as-a-service provider supporting various web and mobile platforms. It provides developers built-in services like realtime database, crash-reporting, authentication, storage, hosting, and a lot of stuff that most systems require.

WhatToDo ( A todo list app)

To familiarize myself with what Firebase can do, I created a simple Todo List Application that demonstrates usage of authentication and database where a user can add tasks on a single list, and automatically saves the data to retain it even when the user signs out from the app. You can checkout the app here: https://fir-js-app.firebaseapp.com/

If you’re curious how the app works, just read on.


Before we proceed with how my simple todo app was created with Firebase. Let’s have an overview of what basic functionalities would the app need.

  1. Authentication: We need authentication so we can identify the user and create a list with his own unique id.
  2. Database: Of course we need this to store the user’s information and the data of his list.

That’s what we will need for the app for now. Now, let’s proceed working on the app.

Starting a Firebase App

To start a Firebase app, you’ll need a Google account to have an access to the Firebase service. So if you still don’t have a Google account, go and register here: https://accounts.google.com/SignUp?hl=en.

When you’re done registering go to Firebase to read about that service or you can go straight ahead to the Firebase Console. On the Firebase Console, you’ll be able to see the welcome screen and a list of your projects but of course if this is your first time then you’ll see an empty list.

Firebase Console Welcome Screen

Now, we should create a project, just click on the Add Project button and you’ll be prompted to enter a project name and to select a Country or Region of the app. Once you’re done filling up the details just hit the Create Project button and you’ll have a Firebase project to work on.

When you’re done with creating an app, you should click on your project from the list to see the Project Dashboard. In this dashboard you’ll be able see the different features or services available for the project, and where you can use them. This is a web app so let’s click on the Add Firebase to your Web App from the Overview.

A popup will appear with the Firebase library you will use and the credentials you need to use the Firebase service on the web app, we should copy this and add to our project.

You would say it would be insecure to have the app’s credentials together with the script. There is a way to secure the credentials but for now let’s just add this issue on our checklist and focus on learning some of the basic functions of Firebase.

This is how I added Firebase on my app.

Now, we’re ready to fire up the app and include what we’re gonna use from the Firebase features. Let’s set it up first.

So here’s what I did:

  1. Initialize the app with the config given for the project from Firebase
  2. Write a variable where we call on the auth() and the database() functions
  3. Add scope and a custom paramerter on the auth provider.
Setting up Firebase

Let’s go to the next step.

Authentication

This is the first thing I’ve worked on the app, we need this to identify the user. We have a number of options we can use to authenticate users. On your project’s dashboard on Firebase, go to Authentication and click Sign-in Method tab.

We can use the classic E-mail/Password authentication, allow anonymous and phone logins, or use sign-in with providers like Google, Facebook, Twitter and Github. By default all of this are disabled, you can click on the provider or method you need to enable it (some of the options may prompt you to give API credetials).

In my app, I used Google as per my example on setting up the Firebase. To sign-i, we can call auth.signInWithPopup(provider).then().catch(); when the user click’s on the login button. And to sign out, call on auth.signOut().then().catch(); .

We can monitor the authentication state with auth.onAuthStateChanged(); . Here is what a usual onAuthStateChanged() looks like.

auth.onAuthStateChanged(user => {
if(user) {
// IF A USER IS LOGGED IN DO YOUR LOGIN ACTIONS HERE
} else {
// IF A USER IS LOGGED OUT DO YOUR LOGOUT ACTIONS HERE
}
});

Here is what my authentication procedure looks like.

Now we’re done with the login let’s work on reading and writing the data.

Read and Write Data

To work with the database we need to call firebase.database() , this initiates a connection to the database. Now let’s see what are the functions we need to read and write data.

If you’re curious what the database looks like on the Firebase project dashboard, click Database on the menu in the right. This is what a filled database looks like.

Get all the data

firebase.database().ref().once('value').then(function(snapshot){
var data = snapshot.val();
});

This reads the whole database once and you can gain access to the data by calling snapshot.val() .

Get data from a certain object

firebase.database().ref('users').once('value')
.then(function(snapshot){
var users = snapshot.val();
  });

This is similar to the query above but it only gets data from a certain object, in this case it’s users.

Getting child objects

var currentUser = firebase.auth().currentUser.uid;
firebase.database().ref('users').child(userId).once('value')
.then(function(snapshot){
var user = snapshot.val();
});
// OR THIS ONE
firebase.database().ref('/users/'+userId).once('value')
.then(function(snapshot){
var user = snapshot.val();
});

If in case you have user data stored in a object with their uid, you can access them by attaching the child() function toref() or concatenating the uid to the ref(), and it will return that certain object.

Writing data

Always remember that when you’re writing data to the firebase, you can’t do it without set an object without a value. For example, I wanted to create an object named playlist I have to initialize it with data or else the object won’t be written to the database at all.

Creating an object

For example, if you want to create a users ref or object you can do this.

firebase.database().ref().child('users').set({
"uid": {
"fake-data":1
}
});

This will create the users object with a fake data, you can always delete them afterwards when you have a real data to store. This is just to setup the objects you need. Personally, I created them manually on my project’s dashboard in the Firebase Console and started with dummy data to see what structure would be best for the app. You can also use this query to create new data for the users object or the object you want to fill data with. Just remember that set() is universally used to write data on firebase. You can also use push() to save data to the database but it will be under an ID that is a string related to a timestamp. If you want to set aunique ID for your objects you can use child('your_id') to set it.

Updating an object

You can use set() or update() to update an object just be careful how you use it because it can rewrite all the data in an object totally.

Removing an object

Let’s say, you want to remove a song from your playlist this is how you would remove it.

var songId = 12;
firebase.database().ref('playlist').remove(songId);

Setting up the database queries

To make things easier, I’ve written all of the database queries in one script and made it globally available so I can access them wherever I want. The registration process and the list events are all in here.

Using the Realtime Database

To use the Realtime Database we must use one Firebase’s event queries. On my app, I used the on('value',fn) event, this event will trigger everytime there is a change on the reference object it is attached to. In my app, I attached this event to the user’s list, identified with his uid on the database. This particular line here on the gist for authentication is what I’m talking about.

listsRefObject = firebase.database()
.ref('lists').child(currentUser.uid);

This is how we attach the value changed event to the reference object.

listsRefObject.on('value', function(snapshot){
var list = snapshot.val();
// Do you thing here like e.g. refreshing the UI.
});

You can check the todo list functions here.

Extra

You can host your app in the Firebase’s Hosting site. Just follow the simple steps from this tutorial video on the official Firebase channel. Just a reminder, you would need Node.js to install their deployment tools.

Conclusion

Firebase is a great service. You should consider using Firebase if you want to create an app quickly that is ready for scaling and production. It provides you with ready-to-use services and features that you mostly need to develop from the ground up, i.e Authentication from third-party services, API Services, and more. Most importantly, it supports a wide range of mobile devices.

Sources