Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Firebase – Google Alphabet’s Cloud Service Provider

4.26/5 (6 votes)
10 Apr 2016CPOL6 min read 13.3K   73  
Firebase, a one stop solution for your web or mobile applications on Cloud powered by Firebase’s NoSQL backend and much more

Introduction

Firebase, a one stop solution for your web or mobile applications on cloud powered by Firebase’s NoSQL backend and much more.

This article is about “Firebase”, Google’s cloud hosted solution with real time NoSQL database. Note: Firebase was acquired by “Google” in October 2014. It’s dedicated to customers in providing a platform for static hosting, authentication, real time database, custom domain, etc.

If you are new to “Firebase”, don’t worry! You are not the only one. Coming to the expectations on this article, it mainly focuses on giving an introduction to “Firebase” with a real world example.

Believe me, in a matter of five minutes, you can make your application up and running on “Firebase” cloud platform.

Features of Firebase

  1. Real time database – Firebase manages all the user data in a NoSQL database with the data stored in JSON format. Firebase synchronizes all its data to connected clients in any platform/device.
  2. Build Cross platform Apps – Firebase lets the customer to focus on their business requirements. Developers have full freedom to choose their preferred programming language or platform for development. Firebase has SDKs for Android, iOS and JavaScript. One can easily consume the “Firebase” REST service and develop apps too.
  3. Security – All firebase transaction happens over highly a secured SSL connection with a 2048-bit certificate.
  4. Offline mechanism – All Firebase based applications let you take advantage of its offline capability. The application will continue to work even if the network connectivity gets lost. Once the application gets the connectivity, The Firebase client makes sure to synchronize the internal version of its data with the Firebase server and other connected clients to its best.

Scenarios of Usage

If you are wondering in what scenarios you can use “Firebase”, here are a few:

  1. You wish to quickly design, develop and deploy your application to cloud by utilizing a highly efficient backend storage.
  2. Say you have an application ready. Now you are thinking of a reliable, scalable and low cost backend support for storage.
  3. Upgrade, downgrade with ease with a free email support for paid plans.
  4. Deploy your solution in no time without having to worry about the infrastructure support for managing the application or data.
  5. You would like to allow your application to be used while the users are online or offline, then you are the right candidate for “Firebase”. All firebase operations like setting (nothing but adding), removing or updating can be accomplished without the network connectivity.

Firebase Pricing

We have to understand the pricing tier before ever we decide and start to deploy our applications on “Firebase”. Here’s the link to understand the pricing tiers.
One can definitely go with a “Free” plan with $0 unlimited users with a storage capacity of 1GB and transfer rate of 10GB.

Background

Minimum knowledge and understanding of AngularJS would help in understanding the article demo code.

Using the Code

Let us take a look into the sample code and try to understand the usage of “Firebase” operations.
We are going to see a tiny “Movie” App, which lets the user to key in their favorite movie and manage the same. The sample application demonstrates the “CRUD” operation against the configured “Firebase” NoSQL database.
The sample demo application is developed in AngularJS. We will be coding an Angular Controller and Factory for managing the favorite movie list in Firebase.

Below are the JavaScript references for our MovieApp.

HTML
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'/>
<script src=https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js/>
<script src=https://cdn.firebase.com/libs/angularfire/0.7.1/angularfire.min.js/>      

Let us create an Angular module by specifying the name and dependencies.

JavaScript
var movieFire = angular.module("MovieFire", ["firebase"]);

Below is a code snippet of MovieApp controller. Here’s what we need:

  1. All the users to key in and save their favorite movie lists
  2. Allow users to edit the movie name
  3. Allow users to delete the movie list item

We are going to define a scope variable for holding the favorite movies. Every time the Firebase movie DB is being updated (added or edited) with a movie name or any delete operation on the movie, the “on” value change event gets fired. The “movies” scope variable is being reset by getting all the key items from Firebase DB and then by looping through and pushing each items (key and value) pair to movies list.

The controller does nothing more than refreshing the movie list and making a call to the factory method to perform saving, editing and deleting the movie item.

JavaScript
function MovieController($scope, $firebase, MovieFactory) {
    $scope.favMovies = $firebase(new Firebase('https://moviefire.firebaseio.com/movies'));
    $scope.movies = [];
    
    $scope.favMovies.$on('value', function() {
        $scope.movies = [];
        var mvs = $scope.favMovies.$getIndex();
        for (var i = 0; i < mvs.length; i++) {
            $scope.movies.push({
                name: $scope.favMovies[mvs[i]].name,
                key: mvs[i]
            });
        };
    });

    $scope.saveToList = function(event){
        if (event.which == 13 || event.keyCode == 13) {
            MovieFactory.saveToList($scope.mvName, $scope.favMovies);
            movieName.value = '';
        }
    }

    $scope.edit = function(index){
        MovieFactory.edit(index, $scope.movies[index].key, $scope.movies[index].name);
    }

    $scope.delete = function(index){
        MovieFactory.del(index, $scope.movies[index].key, $scope.movies[index].name);
    }
}

Below is a code snippet of Angular Factory.

The logic for favorite managing movies are located within this factory. It has a dedicated method for saving, editing and deleting a movie item.

JavaScript
movieFire.factory('MovieFactory', function($firebase){
    var movieCRUDOperations = 
    {
        saveToList : function(name, favMovies) {
            var mvName = name;
            if (mvName.length > 0) {
                favMovies.$add({
                    name: mvName
                });
            }
        },
        edit : function(index, key, name) {
            var newName = prompt("Update the movie name", name); 
            if (newName && newName.length > 0) {
                var updateMovieRef = movieCRUDOperations.buildEndPoint(key, $firebase);
                updateMovieRef.$set({
                    name: newName
                });
            }
        },
        del : function(index, key, name) {
            var response = confirm("Are certain about removing \"" + name + "\" from the list?");
            if (response == true) {
                var deleteMovieRef = movieCRUDOperations.buildEndPoint(key, $firebase);
                deleteMovieRef.$remove();
            }
        },
        buildEndPoint : function(key, $firebase) {
            return $firebase(new Firebase('https://moviefire.firebaseio.com/movies/' + key));
        }

    }
    return movieCRUDOperations;
}); 

Firebase Setup on Tour Local Machine

  • Please download and install NodeJS if you don’t have one - https://nodejs.org/
  • Install Firebase command line tools by running the below command:
    npm install -g firebase-tools
  • If you wish to update firebase tools, just run the below command:
    npm update -g firebase-tools

Firebase Create App

It is recommended to create an app and then host the application.

Image 1

Firebase Initializing

First, you need to run the “firebase init” command so that the Firebase creates necessary files required for deploying your application.

Always use the existing database than creating a new one as Firebase has some issues in creating on the fly.

Choose an existing Firebase database and hit enter to proceed further. Under “What directory should be the public root?”, specify the application folder name, example: movieappdemo and hit enter which will create a firebase.json file. Copy paste or move all your application files to the public root folder. In this case, it would be “movieappdemo” folder will contain HTML, CSS and Angular JS script files.

Image 2

Firebase Deploy

In order for the Firebase deployment, you must follow the previous step of initializing the Firebase.

First, you need to authenticate yourself so you can perform the deployment. Please run the following command to authenticate.

firebase login

Key in the following command to deploy your application to Firebase.

firebase deploy

Image 3

Firebase NoSQL Database Preview

Here’s the screenshot of the Firebase NoSQL database consisting of information in JSON format. Every item in the Firebase DB consists of a key and value pair item.

Image 4

Firebase Movie App Screenshot

Image 5

Note: Any issues with the Firebase deployment. Please take a look here.

The latest up to data AngularJS code is also available here.

References

Below are links which helped me to understand “Firebase”.

The demo app is based on the following open source code:

Points of Interest

Firebase made me think of endless possibilities in developing and deploying applications on cloud platform with Firebase NoSQL Database.

History

  • 04/10/2016: Version 1.0 - Published initial version of the article with the demo code

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)