Setting Up Firebase for Your Next Project

In today's tutorial we will get you up and running with Firebase by building a simple chat room application by leveraging Firebase's Javascript API. This application will provide you with the building blocks to develop more advanced real-time applications on your own projects.

Getting Started

In order to get Firebase up and running, you are going to have to create a free developer account by visiting their website, and registering. Once you have successfully registered, Firebase will redirect you to your account dashboard where you will have access to all of your Firebase data locations and other neat features. However, right now you should select the Firebase data location entitled, MY FIRST APP. Feel free to rename this application or create a new one.

When, the Firebase data location was created, it was assigned its very own unique host-name. This unique host-name is very important; because this is the location where your data will be read from and written too. We will discuss the host-name in more depth, later in the tutorial but for now:

Let's Start Building

The first item on the agenda: create a new HTML file that references the Firebase client, jQuery, and Bootstrap CDNs. It is quite obvious that we need to reference the Firebase CDN. Now, it may not be as clear why we are referencing both jQuery and Bootstrap. I am using both jQuery and Bootstrap for the purpose of rapid application development. Both of these libraries allow me to do things very quickly and they don't require much hand coding. However, I will not be covering either jQuery or Bootstrap in any great detail; so feel free to learn more about these JavaScript libraries on your own.

The HTML

The markup that implements what I described is as follows:

Now that we have our HTML file created and it is referencing the correct CDNs, let's begin working out the rest of our application.

First, We need to determine what essential functionality this application will need. It seems that most chat room style applications have two similarities: a message box for sending messages to a server and a section that gets populated with messages from a server. In our case, this server is going to be our Firebase data location.

Let's implement the message box for sending messages to a server before hand. This will require us to create a simple interface that includes an input field and a submit button wrapped within form tags. Since we are referencing the Bootstrap stylesheet, we have the convenience of using some predefined bootstrap styles to create the interface. As I stated earlier, this is very convenient and allows us to write less code by hand.

So let's first place a div with the class attribute container directly after the opening body tag within the HTML file. This is a bootstrap feature that provides width constraints and padding for the page content. Within the container tags, lets add a title wrapped within H1 tags, so that we can give the application a descriptive name. My title will be, "Firebase Chat Application". Feel free to use your own creativity when writing your title.

The markup that implements what I described above, looks like this:

In addition, we also need to add a div with class attributes: panel and panel-default. A panel is a Bootstrap component that provides a simple box that contains four interior DIVs: panel-heading, panel-title, panel-body, and panel-footer by default. We will not be using panel-heading and panel-title but we will use both panel-body and panel-footer. The panel DIV will be used as the main container for the chat room client.

The markup that implements what I described above, is as follows:

At the moment, we will not be working with the panel-body. However, we will need to use this section later in the tutorial for populating messages from our data location.

Right now we will be focusing on the panel footer div. The panel footer will contain an input field, submit button, and reset button. We will give the input field an attribute id of comments and the submit button an attribute id of submit-btn. Both of these id attributes are very important and will be needed later in the tutorial. Feel free to alter the attribute IDs for the form elements.

The markup that implements what I described above, is as follows:

Now let's implement the JavaScript that will allow us to send the message to our Firebase's data location.

The JavaScript

First we need to add a set of script tags directly above the closing body tag, within the HTML file. Within the script tags, we need to create a reference to our Firebase's data location. Without this reference, we cannot write data to our data location. This can be accomplished by initializing the Firebase constructor and passing our data location as the parameter. Remember, the Firebase data location was created when you setup Firebase (the unique host-name).

The code that implements what I described above, is as follows:

After initializing the Firebase reference object, we need to bind a click event handler to the submit button selector. The location of this selector is within the panel footer. Also, we need to ensure that the event handler callback contains a return false statement as the last line of code. This will ensure that the default action of submitting the form, does not occur and prevent the event from bubbling up the DOM tree. However, in some cases you may want event bubbling to occur.

Both of the JavaScript snippets below implement what is described above:

Next, we will define a variable that references the comment's selector and another variable that removes the white spaces from the beginning and end of the comment's value.

The code that implements what I described above, is as follows:

Now we need to determine the method needed for actually writing theses comments to our data location.

Writing Data to Firebase

Firebase's API offers several methods to write data to a data location. However, in today's tutorial we are going to focus on using the set() and push() methods. Let's briefly review what each of these methods allow us to do.

  • The set() method will write data to the data location, as well as overwrite any data that is currently stored at the data location.
  • The push() method will write data to the data location by automatically generating a new child location with a unique name. In addition, this unique name will be prefixed with a time-stamp. This will allow all the children locations to be chronologically-sorted.

After reviewing both the set() and push() methods; I think it is quite evident that we need to leverage the push() method in our application. Otherwise, we will continuously overwrite the latest comment at our data location and that would be no fun.

To do this, let's jump back to the JavaScript that we previously added to our page. We now need to push the comment value to our data location. Now keep in mind that there are different push methods that allow us to push data in various formats, such as an object, array, string, number, boolean, or null. We will just use an object that has a key value pair of a comment and  a comment value. In addition, we will attach an optional callback to fire after the push methods have finished. The callback will return an error object on failure, and on success, a null value.

The code that implements what I described above, is as follows:

Now let's add something to ensure that the chat room users aren't able to write blank messages to our data location. This can easily be accomplished by adding a simple if else statement that checks the length of the comment's value.

The code that implements what I described above, is as follows:

Great, we've successfully completed the section of our application that allows users to write data to our data location. But, we are sill lacking the functionality that provides users with a real-time chat experience. This type of experience will require the ability to read data from the child locations, within the data location.

Reading Data from Firebase

As we mentioned earlier, most chat room style applications read data from a server and then populate a section of the interface. We will need to do the same thing in our application, by leveraging the Firebase API.

Firebase's API offers several methods to read data from a data location.  In todays tutorial, we are going to focus on using the on() method.

The on() method has several arguments that are worth looking into, but we are only going to cover the first two arguments: eventType and callback. Let's review both of these.

Selecting an eventType

The "eventType" argument has several options. Let's look at each so that we are able to determine which will meet our needs.

  • "value" - will be triggered once, and reads all comments, and every time any comments change it will be triggered again, as well as read all the comments.
  • "child_added" - will be triggered once for each comment, as well as each time a new comment is added.
  • "child_removed" - will be triggered any time a comment is removed.
  • "child_changed" - will be triggered any time a comment is changed.
  • "child_moved" - will be triggered any time a comment's order is changed.

After looking over the above options, it seems quite clear that we should be using "child_added" as our "eventType". This even type will be triggered once for each comment at our data location, as well as each time a new comment is added. In addition, when a new comment is added it will not return the entire set of comments at that location, but just the last child added. This is exactly what we want! There is no need to return the entire set of comments, when a new comment is added.

Analyzing the callback

The "callback" for the on() method provides an item that Firebase refers to as a "snapshot of data” which has several member functions, the focus today is on name() and val().

The name() member function provides us with the unique name of the "snapshot of data". If you remember earlier, we used the push() function to write a new comment to our data location. When push() was called, it generated a new child location using a unique name and that is the name that will be returned via the call back member function,name().

The val() member function provides us with the JavaScript object representation of the "snapshot of data" and with this snapshot, we will be able to retrieve a comment from our data location. However, we need to backtrack for a moment. 

Earlier in this tutorial we implemented the JavaScript needed to push comments to our Firebase location and we did this by pushing an object with a key value pair. In this case, the key was "comment" and the value was the input that the user entered. Therefore, if we want to extract a comment from our "snapshot of data" we need to recognize the correct data type. In this case we are dealing with an object, so you can use either dot notation or bracket notation to access the specified property.

Both of the JavaScript snippets below, implement what is described above:

Rendering the Comments

Next let's create a simple, yet clean way to display each comment. This can easily be achieved by wrapping each comment within a div and labeling each comment with its unique name. Usually comments are labeled with the user's name that wrote that comment, in our case, this is an anonymous chat room client.

The code that implements what I described above, is as follows:

Next we must append each comment to the comment's container and get the current vertical position of the comment's container scrollbar and scroll to that latest location. This will ensure that each time a comment is pushed to Firebase, all users using the chat application will see the latest comment made. All of this must be done within the callback.

It should look something like this:

Now lets apply some simple CSS styles to the DIVs wrapped around each comment block. This will make the appearance slightly more attractive and user friendly. These styles should be added within the style tags, located in the head section of the HTML.

The code that implements what I described above, is as follows:

Running the Application

It's now time to run our application. Lets begin by opening up two instances of our favorite, modern browser and placing them side by side on our desktop. Next, we will browse to the file location of our file that we created, on both browsers. Test it out by writing a few comments and enjoy watching the magic of Firebase. 

It is unbelievable that only a couple lines of code can produce such a powerful application. Feel free to edit this snippet in any way to produce your desired results.

Check out the online demo to see it in action. Below is the complete source code for the entire chat room application:

In Summary

In today's tutorial, we worked all the way through the process of implementing a simple chat room application by leveraging Firebase's JavaScript API. In doing so, we were able to experience the power of Firebase and gain an appreciation for its convenience. Below are some of the key items that we hit on today:

  • Referencing a Firebase data location by initializing a Firebase constructor.
  • Writing data to Firebase by using the push method.
  • Reading data from Firebase by using the on method with the event type "child_added".

I hope this tutorial has given you the starting point you need to take things further with Firebase. If you have any questions or comments, feel free to leave them below. Thanks again for your time and keep exploring the endless possibilities of the Firebase API.

Resources

Tags:

Comments

Related Articles