Getting started with Firebase, by building a persistent chat client

Screenshot 2015-08-07 14.05.09

I recently utilized Firebase to power the database and back end of an AngularJS web application I’ve been working on.

Firebase was proved to be amazingly easy to setup. Their “5 minute quick start” sold me on the utility of this service.

How easy is it? Let’s go ahead and create ourselves a persistent chat client in about 5 minutes. I’ll assume you’ve had some previous experience with Angular, but it’s not required.

In an empty HTML page, let’s add the Firebase Javascript library in the head section of our page.

<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>

Alright, easy enough, right?

Now, you need to create a reference to your Firebase database inside your script tag. When you sign up (for a free, even!), Firebase will give you a random URL that links to your new database.

So, a reference in your script tag, like so:

  <script>
    var myData = new Firebase('https://d______.firebaseio.com/');
  </script>

Okay, okay. Not too bad.

How do you start sending data to your new Firebase DB? You just apply some Firebase methods to the reference we created about. In this case, we’ll use the set() method.

  // Store values from our input boxes here.
  var name, text; 

  // jQuery or other magic here to set input boxes
  // to the values above.

  // Save to our Firebase DB using the .set() method.
  myDataRef.set('User ' + name + ' says ' + text);

You’d likely use jQuery to set the values of a particular input box to the name and text. You can also pass in objects to the set() method like so:

  myDataRef.set({name: name, text: text});

Another option that you can utilize to store data inside Firebase is the push() method. You can utilize this method to easily create lists of objects.

  myDataRef.push({name: name, text: text});

Okay, we talked a lot about how to send messages to our database. But how do we retrieve them? We can create an event listener using the on() method, like so:

  myDataRef.on('child_added', function(snapshot) {
    var message = snapshot.val();
    displayChatMessage(message.name, message.text);
  });

And just like that, you now have a working chat client supporting many users and can share data to all clients using it. Amazing!

Leave a Reply

Your email address will not be published. Required fields are marked *