Getting started with Firebase

Tweet about this on TwitterShare on LinkedIn1Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page

Getting started with Firebase

In this post, we will see how to integrate Firebase with a “Pure” Javascript application, an Angularjs application and a Backbonejs application. We will start off by setting up Firebase account and then we will take a quick look at the Firebase Authentication API. I have also written a Hybrid app using Firebase and IonicFramework, you can find the details below.

We are going a MovieFire app, that will store all your favorite movies. And to persist this data, we will integrate the app with Firebase. We will be implementing the traditional CRUD operations on the movies collection.

You can take a quick peek at the demo here

Screen Shot 2014-06-27 at 10.26.25 am

and the complete code here.

So, Let’s get started.

Contents

What is Firebase?

Firebase is a real time application platform. It allows developers to build rich, collaborative applications quickly using just client-side code. Applications built with Firebase:

  • Can be built rapidly
  • Update in realtime out-of-the-box
  • Remain responsive even when a network connection is unavailable

Setup Firebase

If you do not have a Firebase account already, you can navigate to the Signup page and create an account. If you already have one, you can Login.

Once you are on your Account’s page, you will have an option to create a new Firebase app.

You can create a new app like

Screen Shot 2014-06-22 at 11.32.00 amSince I have already take this sub-domain, you have to use another name. Once the app is created, click on the Manage App button.

After redirection, This is an overview of your App’s backend. Here, you will configure all the rules and setting that come out-of-the-box. These options are pretty comprehensive and all you need to build quick and real time apps.

Take a few moments and browse through the settings before continuing.

Firebase Authentication

Firebase has an awesome out-of-the-box authentication system and you can pick from any of the below providers

  • Facebook
  • Twitter
  • GitHub
  • Google
  • Persona
  • Email
  • Anonymous

And integrating these providers into your app is also pretty simple. You can check out this on how to implement authentication.

In this post, we will be dealing with only the CRUD operations on a collection.

jsFire App

We will start off by building a “Pure” Javascript application and then we will integrate Firebase into it.

Create a new folder named myFirebaseApp and inside that folder, create a new folder named jsFire.

Next, create app.html, app.js and app.css at the root of the jsFire folder. We will build a simple UI, that will provide a textbox to enter a movie name. And we have a list item view, where we display all the entered movies.

Open up app.html in your favorite editor and add the below markup

Next, open app.css and add the below styles

And finally open app.js and add the below script

That is all you need to run the app.

You can either the host this app on a *AMP server and navigate to the app.html or simple open app.html in your browser (with file:///…), you should see

Screen Shot 2014-06-22 at 12.35.07 pm

You can enter a movie name and hit return and you should see

Screen Shot 2014-06-22 at 12.36.50 pm

Simple and sweet right? But if you refresh, all the data will be lost. This is where we bring in Firebase.

Open app.html and add the below script reference above the app.js reference.

<script type='text/javascript' src='https://cdn.firebase.com/js/client/1.0.15/firebase.js'></script>

This is all we need to import the goodness of Firebase in our app. Next, open up app.js and update it as below

We have changed the code quite a bit since the first version. Things to notice

Line 1 : We will create a reference to a collection present on Firebase Data Store. If the reference does not exist, Firebase will create one for you as soon as you save the first piece of data. Update this link with your Firebase instance.

Line 6 : If the user hits the enter key and there is valid data in the input box, we pass the contents of the textbox to  saveToFB().

Line 14 : Here we refer to the earlier created instance of  favMovies and access the  push() to push the movie name to the movies collection. Once the data is saved, FB will fire a value event, invoking Line 30.

Line 30 : As soon as a new instance of movies collection is created, FB client API will fetch all the items in collection for you and will fire a value event. We will take advantage of this event to populate the UI with already saved list on page load. And this same code will be used to update the data on Save.

Line 31 : This is how the data will look when it comes from the server

Screen Shot 2014-06-22 at 1.13.34 pmWe will iterate over each object and display the name. We will also save the key of the object. This will be used to perform Updation and Deletion activities.

Line 37 : Once the data is pruned, we will build an object with the movie name and the key and pass it to the refreshUI() .

Line 21 : Here, we take in the object and build the list items.

Now, you can refresh your UI and add a few names. This should work as earlier. Refresh the page again and you should see your earlier saved movie names. Bam!!

Isn’t this awesome or what? We did not even write a single line of server code!

Realtime Updates

Now, open up 2 browsers and launch app.html.

Screen Shot 2014-06-22 at 1.28.57 pmAnd update the movie name in one browser and you should see the data updating in the other one without refreshing

Screen Shot 2014-06-22 at 1.29.12 pmAnd now, if you go back to your Mange App page on Firebase and click on the data tab, you should see

Screen Shot 2014-06-22 at 1.32.36 pm

The data gets updated on all the clients as well as the FB data store at the same.

Wondering How?

Firebase uses Sockets to achieve the real time data management. You can launch chrome, open the dev tools and then launch your page. You should see something like

Screen Shot 2014-06-22 at 1.37.22 pmAnd when you add a new movie (and reclick on wss request) you should see

Screen Shot 2014-06-22 at 1.38.59 pmAwesome right?

Update and Delete

So far, we have implemented Create and Read. Now we will implement Update and Delete. Open app.js and update the code as below

Line 24 : We are adding the Edit and Delete links to the li.

Line 29 : Will generate the links for us and return the markup to be updated on Line 24. genLinks() will take in the key and text of the movie and generate 2 links that call either  edit() or  update() with these parameters on clicking them.

Line 36 : This will be triggered when you click on the edit link. First we throw a prompt asking the user to update the name. When done, we check if the data is valid and then we update the data by creating an instance of the item in the collection.

Line 56 : Will create a new FB instance of the movie name using the key passed to it. This reference can be used further to perform operation on this specific item in the collection.

Line 41 : We use the newly created reference and call the update() on it passing the value to be updated. Once the data is updated, FB will trigger the value  event and the list will refresh automagically.

Line 47 : When the user clicks on the delete links, we ask the user to confirm his decision. Once the user confirms, we create an instance of the movie name and issue a remove command. And again FB will take care of triggering the  value  event.

Now, save the file and back to browser and refresh

Screen Shot 2014-06-22 at 2.50.42 pmNow click on the edit link and update the value like

Screen Shot 2014-06-22 at 2.51.55 pmand the UI will get updated

Screen Shot 2014-06-22 at 2.52.30 pmNow when you click on Delete Screen Shot 2014-06-22 at 2.53.24 pmAnd confirm, the movie name will be deleted

Screen Shot 2014-06-22 at 2.54.11 pmAnd now you can sing Create Read Update Delete.. Create Read Update Delete.. LOL.

Now, we understand the power of “Zero Code – Server as a Service“, let’s see how this can make client side frameworks even more powerful.

ngFire App

If you have jumped to this section directly, I would recommend reading the jsFire section first, as I would be running through most of the things quickly here.

We will be implementing the same MovieFire app, but using Angularjs.

Note : I am assuming that you are already aware of Angularjs.

You can use slush-angularfire to scaffold a Angular FIre base for you or you can follow the below steps to create it from scratch.

Create a new folder inside myFirebaseApp and name it ngFire. Next, Create 3 new files app.html, app.js and app.css.

Open app.html in your favorite editor and add the below code

Line 22/23/24 : Add references to Firebase, Angularjs and AngularFire

Line 2 : We add the ng-app  directive

Line 9 : We add the ng-controller  directive

Line 13 : We add the ng-model  directive to the input box to read the value

Line 17 :  We use ng-repeat  directive to generate the movie name text, edit and delete links. Unlike jsFire, we will not be passing the key and value, but we will pass the index of the array. In the controller, we will fetch the movie item at runtime from the scope.

Now, we will define our angular app and create the controller used above. Open app.js and update as

Line 1 : We create a new angular module and inject firebase as a dependency.

Line 3 : Define the MainController

Line 4 : Create a new instance of Firebase and wrap it with AngularFire. Do not forget to update your firebase URL here

Line 6 : The  value event that will be triggered whenever the collection is modified. For our example, we need the key of the collection item, so that we can edit and delete it. For that we will be using  $scope.favMovies.$getIndex() to get all the indexes. Then we will build the movie object and update $scope.movies. This is the variable that binds the list items on the UI.

Line 21 : $add method inserts the data to the collection

Line 35 :  $set  method updates the data

Line 47 : $remove  method removes the item from collection

And our app.css would contain

Now, you can view app.html in your browser and it should work exactly the same.

backFire App

If you have jumped to this section directly, I would recommend reading the jsFire section first, as I would be running through most of the things quickly here.

We will be implementing the same MovieFire app, but using Backbonejs.

Note : I am assuming that you are already aware of Backbonejs.

Create a new folder inside myFirebaseApp and name it backFire. Next, Create 3 new files app.htmlapp.js and app.css.

Open app.html in your favorite editor and add the below code

Lines 19-24 : Include Backbone, Firebase and their dependencies

Line 27 : Added a backbone template that will be used to scaffold a new Movie Item

Next, open app.js and update it as below

Line 75 : A new instance of App View is created.

Line 48 : We create a new App level Backbone view. We register the required events to add a new movie and start listening to the add event on the collection.

Line 67 : Will get triggered when a new item is added to the collection. This happens when the page loads and the data is synced with FB and when we add a new movie.

Line 3 : Create a new Backbone model.

Line 11 : Create a new Backbone.Firebase collection. We pass in the model and our Firebase instance URL.

Line 16 : Initialize the collection

Line 18 : Create the Movie Item list view. On initializing, we will register change and remove events. We also bind events to the Edit and Delete links, that are rendered with each movie name item.

Line 29 : This will append a new view to the ol with the model provided.

Line 57 : When the user enters a new Movie name, we add the movie to the collection using add() .

Line 32 : When the edit link is clicked this method will be invoked. Once the user updates the data we use set()  to update the data and backFire takes care of syncing.

Line 40 : When the delete link is clicked this method will be invoked. Once the user confirms the deletion, we will use  remove()  to remove the model from the collection and backFire will sync it for us.

And finally some styles. Update app.css with below styles

Now, you can view app.html in your browser and it should work exactly the same.

ionicFire hybrid App

I have build an Hybrid app leveraging the power of Firebase as a REST server and Ionic Framework to build the UI and interact wit it. You can find the complete article at Creating a Firebase Powered End to End Ionic Application.

Hope you got a basic idea on how to integrate Firebase with your application. I will try to add Firebase integration with Emberjs soon.


Thanks for reading! Do comment.
@arvindr21

Tweet about this on TwitterShare on LinkedIn1Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page
  • Ros Nia

    thanks for ur tutorian , its great :)

  • Ros Nia

    if i want to add the input data part, on which part i can fix it? please help me

  • Kiran Dev

    Nice Tutorial!

    we need More :)

  • Rohit Dandnayak

    Great! Thanks.

  • Javier Mendez

    Great tutorial! I do have one question, how could I replace the remove functionality so it will read the key of the object instead of the the $index so if I change the the order of the list using angularjs orderBy I could still delete the objects?

  • AkiKirai

    Thanks for TUT :)).

  • Jenny Tong

    Great tutorial. One nit: the URL https://cdn.firebase.com/v0/firebase.js is deprecated and loads a very old version of Firebase. You probably want to update it to a more recent version that includes a lot of bug fixes: https://cdn.firebase.com/js/client/1.0.21/firebase.js

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks @jenny_tong:disqus. Fixed the link,

  • Anil S

    Thanks for the tutorial Arvind. i faced a issue. the app is not loading with the latest angularfire cdn version 0.8.0. with 0.7.1 its working fine.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks Anil!
      Wat do you mean by app is not loading? Do you see any specific error?

      — Thanks.

      • Anil S

        Nothing happens when enter key is pressed.

        • http://thejackalofjavascript.com/ Arvind Ravulavaru

          Are you seeing any script errors in the developer console? Is the issue with the pure javascript version or angularjs or backbonejs?

          • Anil S

            angularjs version. only when i add the angularfire cdn link 0.8.0 the app is not working. when changed to older version mentioned in the tutorial 0.7.1 is working fine. in the developer console is see a error $scope.favMovies.$on is not a function (mozilla) and in chrome console it says undefined not a funciton

          • http://thejackalofjavascript.com/ Arvind Ravulavaru

            Please refer to this table : https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-getting-started

            This has the version compatibility details

          • Anil S

            Ya Got it….in the documentation it says ”

            $on no longer exists, similar functionality can be obtained with
            $watch but should be discouraged for trying to manually manage server
            events (manipulation should be done with data transformations through
            $extendFactory instead).”

            so i will have to make changes in “$scope.favMovies.$on” in the MainController.

          • http://thejackalofjavascript.com/ Arvind Ravulavaru

            Oh! I was not aware of it. Thanks for sharing Anil!

  • studiorooster

    Arvind…This is exactly what I was looking for to start my Quality Control application. I am still noobish at Angular and had a quick question. The app is using SimpleLogin, yet, when I register an account from the app, it doesn’t update the info in my Firebase. It only updates the Firebase when I add a bucket list item. Is it supposed to update the user registration info upon registration? Thank you again; I am excited I found your website.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      @studiorooster:disqus Thanks!!

      If you are referring you to the Bucket List application, the registration details will be available in the Firebase forge for this app.

      Firebase App (Forge) >> Simple Login (tab) >> Registered Users (at the bottom of the page)

  • http://www.venkatapathirajum.com VenkatapathiRaju Mandapati

    Great tutorial man. Perfect kickstart.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks @venkatapathirajum:disqus