Friday 27 January 2017

Firebase

Firebase Tutorial

Firebase is backend platform for building Web, Android and IOS applications. It offers real time database, different APIs, multiple authentication types and hosting platform.

Firebase - Overview

As per official Firebase documentation −
Firebase can power your app's backend, including data storage, user authentication, static hosting, and more. Focus on creating extraordinary user experiences. We'll take care of the rest. Build cross-platform native mobile and web apps with our Android, iOS, and JavaScript SDKs. You can also connect Firebase to your existing backend using our server-side libraries or our REST API.

Firebase Features

  • Realtime Database − Firebase supports JSON data and all users connected to it receive live updates after every change.
  • Authentication − You can use anonymous, password or different social authentication.
  • Hosting − The apps can be deployed over secured connection to Firebase servers.

Firebase Advantages

  • It is simple and user friendly. No need for complicated configuration.
  • The data is realtime which means that every change will automatically update connected clients.
  • Firebase offers simple control dashboard.
  • There are number of useful services to choose from.

Firebase Limitations

  • Firebase free plan is limited to 50 Connections and 100mb of storage.

 

Firebase - Environment Setup

In this tutorial we will show you how to add Firebase to existing app. We will need NodeJS. Check the link from the table below if you don't have it already.
S.No.Software & Description
1
NodeJS and NPM
NodeJS is the platform needed for Firebase development. Checkout our NodeJS Environment Setup.

Step 1 - Create Firebase Account

You can create Firebase account here.

Step 2 - Create Firebase App

You can create new app from the dashboard page. The image below shows the app we created. We can click Manage App button to enter the app.
Firebase Environment Setup

Step 3a - Create basic HTML/js App

You just need to create folder where your app will be placed. Inside that folder we will need index.html and index.js files. We will add Firebase to header of our app.

index.html

<html>
   <head>
      <script src = "https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script>
      <script type = "text/javascript" src = "index.js"></script>
   </head>
 
   <body>

   </body>
 
</html>

Step 3b - Use NPM or Bower

If you want to use your existing app, you can use Firebase NPM or Bowers packages. Run one of the following command from your apps root folder.
npm install firebase --save
bower install firebase

 

Firebase - Data

The farebase data is representing JSON objects. If you open your app from Firebase dashboard, you can add data manually by clicking + sign.
We will create simple data structure. You can check the image below.
Firebase Data Simple
In our last chapter we connected Firebase to our app. We can log firebase to console.
console.log(firebase)
Firebase Data Log
We can create a reference to our players collection.
  
var ref = firebase.database().ref('players');

console.log(ref);
We can see the following result in console.
Firebase Data Players Log
 

Firebase - Arrays

This short chapter will show you Firebase representation of arrays.
We will use the same data from the last chapter.
Firebase Arrays Simple
We could create this data by sending the following JSON tree to players collection.
['john', 'amanda']
This is because Firebase doesn't support Arrays directly, but it creates list of objects with integers as key names.
The reason for not using arrays is because Firebase acts as a real time database and if couple of users were to manipulate arrays at the same time, the end result could be problematic since array indexes are constantly changing.
The way Firebase handles it, the keys (indexes) will always stay the same. We could delete 0/john and amanda would still have key (index) 1.
Firebase Arrays Changed
 

Firebase - Write Data

In this chapter we will show you how to save your data to Firebase.

Set

The set method will write or replace data on specified path. Let's create reference to players collection and set two players.
var playersRef = firebase.database().ref("players/");

playersRef.set({
   John: {
      number: 1,
      age: 30
   },
 
   Amanda: {
      number: 2,
      age: 20
   }
});
We will see the following result.
Firebase Write Data Set

Update

We can update Firebase data in similar fashion. Notice how we are using players/john path.
var johnRef = firebase.database().ref("players/John");

johnRef.update({
   "number": 10
});
When we refresh our app, we can see that the Firebase data is updating.
Firebase Write Data Update
 

Firebase - Write List Data

In our last chapter we showed you how to write data in FIrebase. Sometimes you need to have unique identifier for your data.
When you want to create unique identifiers for your data, you need to use push instead of set.

Push

The push() method will create unique id when the data is pushed. If we want to create our players from the last chapters with unique id, we could use the code snippet below.
var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');

var playersRef = ref.child("players");
playersRef.push({
   name: "John",
   number: 1,
   age: 30
});

playersRef.push({
   name: "Amanda",
   number: 2,
   age: 20
});
Now our data will look differently. The name will just be a name/value pair like the rest of the properties.
Firebase Write List Data Push

Key

We can get any key from Fireabse by using key() method. For example, if we want to get our collection name, we could use the following snippet.
var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');

var playersRef = ref.child("players");

var playersKey = playersRef.key();
console.log(playersKey);
The console will log our collection name (players);
Firebase Write List Data Key
More on this in our next chapters.

 

Firebase - Write Transactional Data

Transactional data is used when you need to return some data from the database, make some calculation with it and store it back.
Let's say we have one player inside our player list.
Firebase Write Transactional Data Start
We want to retrieve property, add one year of age and return it back to Firebase.
The amandaRef is retrieving age from the collection and then we can use transaction method. We will get the current age, add one year and update the collection.
var ref = new Firebase('https://tutorialsfirebase.firebaseio.com');

var amandaAgeRef = ref.child("players").child("-KGb1Ls-gEErWbAMMnZC").child('age');

amandaAgeRef.transaction(function(currentAge) {
   return currentAge + 1;
});
If we run this code, we can see that the age value is updated to 21.
Firebase Write Transactional Data Update
 

Firebase - Read Data

In this chapter we will show you how to read Firebase data.
The following image shows the data we want to read.
Firebase Read Data DB
We can use on() method to retrieve data. This method is taking event type "value" and retrieves snapshot of the data. When we add val() method to snapshot, we will get Javascript representation of the data.

Example

var ref = firebase.database().ref();

ref.on("value", function(snapshot) {
   console.log(snapshot.val());
}, function (error) {
   console.log("Error: " + error.code);
});
If we run the following code, our console will show the data.
Firebase Read Data Log
In our next chapter, we will explain other event types that you can use for reading data.

 

Firebase - Event Types

Firebase offers several different event types for reading data.

value

The first event type is value. We showed you how to use value in our last chapter. This event type will be triggered every time the data changes and it will retrieve all data including children.

child_added

This event type will be triggered once for every player and every time new player is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list.

Example

var playersRef = firebase.database().ref("players/");

playersRef.on("child_added", function(data, prevChildKey) {
   var newPlayer = data.val();
   console.log("name: " + newPlayer.name);
   console.log("age: " + newPlayer.age);
   console.log("number: " + newPlayer.number);
   console.log("Previous Player: " + prevChildKey);
});
We will get the following result.
Event Type Child Added Log
If we add new player named Bob, we will get the updated data.
Event Type Child Added Updated Log

child_changed

This event type is triggered when the data has changed.

Example

var playersRef = firebase.database().ref("players/");

playersRef.on("child_changed", function(data) {
   var player = data.val();
   console.log("The updated player name is " + player.name);
});
We can change Bob to Maria in Firebase to get the update.
Event Type Child Changed Log

child_removed

If we want to get access of deleted data, we can use child_removed event type.

Example

var playersRef = firebase.database().ref("players/");

playersRef.on("child_removed", function(data) {
   var deletedPlayer = data.val();
   console.log(deletedPlayer.name + " has been deleted");
});
Now we can delete Maria from the Firebase to get the notification.
Event Type Child Deleted Log
 

Firebase - Detaching Callbacks

This simple chapter will show you how to detach callbacks in Firebase.

Detach Callback for Event Type

Let's say we want to detach callback for a function with value event type.

Example

var playersRef = firebase.database().ref("players/");

ref.on("value", function(data) {
   console.log(data.val());
}, function (error) {
   console.log("Error: " + error.code);
});
We need to use off() method. This will remove all callbacks with value event type.
playersRef.off("value");

Detach All Callbacks

When we want to detach all callbacks, we can use −
playersRef.off();

 

Firebase - Queries

Firebase offers various ways of ordering data. In this chapter we will show simple query examples.
We will use the same data from our last chapter.
Firebase Queries Data

Order By Child

To order data by name, we can use the following code.

Example

var playersRef = firebase.database().ref("players/");

playersRef.orderByChild("name").on("child_added", function(data) {
   console.log(data.val().name);
});
We will see names in alphabet order.
Firebase Queries Order By Child

Order By Key

We can order data by key in similar fashion.

Example

var playersRef = firebase.database().ref("players/");

playersRef.orderByKey().on("child_added", function(data) {
   console.log(data.key);
});
Firebase Queries Order By Key

Order By Value

We can also order data by value. Let's add ratings collection in Firebase.
Firebase Queries Rating Data
Now we can order data by value for each player.

Example

var ratingRef = firebase.database().ref("ratings/");

ratingRef.orderByValue().on("value", function(data) {
   data.forEach(function(data) {
      console.log("The " + data.key + " rating is " + data.val());
   });
});
Firebase Queries Rating Log
 Firebase offers various ways of ordering data. In this chapter we will show simple query examples.
We will use the same data from our last chapter.
Firebase Queries Data

Order By Child

To order data by name, we can use the following code.

Example

var playersRef = firebase.database().ref("players/");

playersRef.orderByChild("name").on("child_added", function(data) {
   console.log(data.val().name);
});
We will see names in alphabet order.
Firebase Queries Order By Child

Order By Key

We can order data by key in similar fashion.

Example

var playersRef = firebase.database().ref("players/");

playersRef.orderByKey().on("child_added", function(data) {
   console.log(data.key);
});
Firebase Queries Order By Key

Order By Value

We can also order data by value. Let's add ratings collection in Firebase.
Firebase Queries Rating Data
Now we can order data by value for each player.

Example

var ratingRef = firebase.database().ref("ratings/");

ratingRef.orderByValue().on("value", function(data) {
   data.forEach(function(data) {
      console.log("The " + data.key + " rating is " + data.val());
   });
});
Firebase Queries Rating Log
 

Firebase - Filtering Data

Firebase offers several ways of filtering data.

Limit to First and Last

limitToFirst method returns specified number of items beginning from the first one.
limitToLast method returns specified number of items beginning from the last one.
Our example is showing how this works. Since we only have two players in database, we will limit queries to one player.

Example

var firstPlayerRef = firebase.database().ref("players/").limitToFirst(1);

var lastPlayerRef = firebase.database().ref('players/').limitToLast(1);

firstPlayerRef.on("value", function(data) {
   console.log(data.val());
}, function (error) {
   console.log("Error: " + error.code);
});

lastPlayerRef.on("value", function(data) {
   console.log(data.val());
}, function (error) {
   console.log("Error: " + error.code);
});
Our console will log first player from the first query, and the last player from the second query.
Firebase Filtering Data Limit to First Last

Other Filters

We can also use other Firebase filtering methods. startAt()endAt() and equalTo() can be combined with ordering methods. In our example, we will combine it with orderByChild() method.

Example

var playersRef = firebase.database().ref("players/");

playersRef.orderByChild("name").startAt("Amanda").on("child_added", function(data) {
   console.log("Start at filter: " + data.val().name);
});

playersRef.orderByChild("name").endAt("Amanda").on("child_added", function(data) {
   console.log("End at filter: " + data.val().name);
});

playersRef.orderByChild("name").equalTo("John").on("child_added", function(data) {
   console.log("Equal to filter: " + data.val().name);
});

playersRef.orderByChild("age").startAt(20).on("child_added", function(data) {
   console.log("Age filter: " + data.val().name);
});
First query will order elements by name and filter from the player with the name Amanda. The console will log both players.
The second query will log "Amanda" since we are ending query with this name.
Third one will log "John" since we are searching for player with that name.
The fourth example is showing how we can combine filters with "age" value. Instead of string we are passing number inside startAt() method since age is represented by a number value.
Firebase Filtering Data Start End Equal

Firebase - Best Practices

In this chapter we will go through Firebase best practices.

Avoid Nesting Data

When you fetch the data from Firebase, you will get all of the child nodes. This is why deep nesting isn't the best practice.

Denormalize Data

When you need deep nesting functionality, consider adding couple of different collections even when you need to add some data duplication and use more than one request to retrieve what you need.

Firebase - Email Authentication

In this chapter we will show you how to use Firebase Email/Password authentication.

Create user

To authenticate user, we can use createUserWithEmailAndPassword(email, password) method.

Example

var email = "myemail@email.com";
var password = "mypassword";

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
   console.log(error.code);
   console.log(error.message);
});
We can check Firebase dashboard and see that user is created.
Firebase Email Authentication User

Sign In

Sign in process is almost the same. We are using signInWithEmailAndPassword(email, password) to sign in user.

Example

var email = "myemail@email.com";
var password = "mypassword";

firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
   console.log(error.code);
   console.log(error.message);
});

Signout

And finally we can logout user with signOut() method.

Example

firebase.auth().signOut().then(function() {
   console.log("Logged out!")
}, function(error) {
   console.log(error.code);
   console.log(error.message);
});

 

Firebase - Google Authentication

In this chapter we will show you how to set up Google authentication in Firebase.

Step 1 - Enable Google Authentication

Open Firebase dashboard and click Auth in left side menu. To open list of available methods, you need to click on SIGN_IN_METHODS in tab menu.
Now you can choose Google from the list, enable it and save it.

Step 2 - Create Buttons

Inside our index.html we will add two buttons.

index.html

<button onclick = "googleSignin()">Google Signin</button>
<button onclick = "googleSignout()">Google Signout</button>

Step 3 - Signin and Signout

In this step we will create Signin and Signout functions. We will use signInWithPopup() and signOut() methods.

Example

var provider = new firebase.auth.GoogleAuthProvider();

function googleSignin() {
   firebase.auth()
   
   .signInWithPopup(provider).then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
  
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
  
      console.log(error.code)
      console.log(error.message)
   });
}

function googleSignout() {
   firebase.auth().signOut()
 
   .then(function() {
      console.log('Signout Succesfull')
   }, function(error) {
      console.log('Signout Failed')  
   });
}
After we refresh the page, we can click on Google Signin button to trigger Google popup. If signing in is successful, developer console will log our user.
We can also click Google Signout button to logout from the app. The console will confirm that the logout was successful.
Firebase Google Auth Log
 

Firebase - Facebook Authentication

In this chapter we will authenticate users with Firebase Facebook auth.

Step 1 - Enable Facebook Auth

We need to open Firebase dashboard and click Auth in side menu. Next we need to choose SIGN-IN-METHOD in tab bar. We will enable Facebook auth and leave this open since we need to add App ID and App Secret when we finish step 2.

Step 2 - Create Facebook App

To enable Facebook authentication, we need to create Facebook app. Click on this link to start.
Once the app is created, we need to copy App ID and App Secret to Firebase page we left open in step 1.
We also need to copy OAuth Redirect URI from this window into Facebook app. You can find + Add Product inside side menu of Facebook app dashboard.
Choose Facebook Login and it will appear in side menu.
You will find input field Valid OAuth redirect URIs where you need to copy OAuth Redirect URI from Firebase.

Step 3 - Connect to Facebook SDK

Copy the following code at the beginning the body tag in index.html. Be sure to replace 'APP_ID' to your app id from Facebook dashboard.

Example

<script>
   window.fbAsyncInit = function() {
      FB.init({
         appId      : 'APP_ID',
         xfbml      : true,
         version    : 'v2.6'
      });
   };

   (function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
 
</script>

Step 4 - Create Buttons

We set everything in first three steps, now we can create two buttons for login and logout.

index.html

<button onclick = "facebookSignin()">Facebook Signin</button>
<button onclick = "facebookSignout()">Facebook Signout</button>

Step 5 - Create Auth Functions

This is the last step. Open index.js and copy the code below.

index.js

var provider = new firebase.auth.FacebookAuthProvider();

function facebookSignin() {
   firebase.auth().signInWithPopup(provider)
   
   .then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
  
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      console.log(error.code);
      console.log(error.message);
   });
}

function facebookSignout() {
   firebase.auth().signOut()
   
   .then(function() {
      console.log('Signout successful!')
   }, function(error) {
      console.log('Signout failed')
   });
}

 

Firebase - Twitter Authentication

In this chapter we will explain how to use Twitter authentication.

Step 1 - Create Twitter App

You can create Twitter app on this link.
Once your app is created click on Keys and Access Tokens where you can find API Key and API Secret. You will need this in step 2.

Step 2 - Enable Twitter Auth

In your Firebase dashboard side menu you need to click Auth. Then open SIGN-IN-METHOD tab. Click on Twitter to enable it. You need to add API Key and API Secret from the step 1.
Below you need to copy callback URL and paste it in your Twitter app. You can find (Callback URL) of your Twitter app when you click on Settings tab.

Step 3 - Add Buttons

In this step we will add two buttons inside body tag of index.html.

index.html

<button onclick = "twitterSignin()">Twitter Signin</button>
<button onclick = "twitterSignout()">Twitter Signout</button>

Step 4 - Auth Functions

Now we can create functions for Twitter auth.

index.js

var provider = new firebase.auth.TwitterAuthProvider();

function twitterSignin() {
   firebase.auth().signInWithPopup(provider)
    
  .then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
  
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      console.log(error.code)
      console.log(error.message)
   });
}

function twitterSignout() {
   firebase.auth().signOut()
   
   .then(function() {
      console.log('Signout successful!')
   }, function(error) {
      console.log('Signout failed!')
   });
}
When we start our app, we can sigin or signout by clicking the two buttons. Console will confirm that authentication is successful.
Firebase Twitter Auth Log
 

Firebase - Github Authentication

In this chapter we will show you how to authenticate users using Github API.

Step 1 - Enable Github Auth

Open Firebase dashboard and click Auth from the side menu and then SIGN-IN-METHOD in tab bar.
You need enable Github authentication and copy Callback URL. You will need this in step 2. You can leave this tab open since you will need to add Client ID and Client Secret once you finish step 2.

Step 2 - Create Github App

Follow this link to crate Github app.
You need to copy Callback URL from Firebase into Authorization callback URL field.
Once your app is created you need to copy Client Key and Client Secret from Github app to Firebase.

Step 3 - Create Buttons

We will add two buttons in body tag.

index.html

<button onclick = "githubSignin()">Github Signin</button>
<button onclick = "githubSignout()">Github Signout</button>

Step 4 - Create Auth Functions

We will create functions for signin ans signout inside index.js file.

index.js

var provider = new firebase.auth.GithubAuthProvider();

function githubSignin() {
   firebase.auth().signInWithPopup(provider)
   
   .then(function(result) {
      var token = result.credential.accessToken;
      var user = result.user;
  
      console.log(token)
      console.log(user)
   }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
  
      console.log(error.code)
      console.log(error.message)
   });
}

function githubSignout(){
   firebase.auth().signOut()
   
   .then(function() {
      console.log('Signout successful!')
   }, function(error) {
      console.log('Signout failed')
   });
}
Now we can click on buttons to trigger authentication. Console will show that the authentication is succesful.
Firebase Github Auth Log
 

Firebase - Anonymous Authentication

In this chapter we will authenticate users anonymously.

Step 1 - Enable Anonymous Auth

This is the same process as in our previous chapters. You need to open Firebase dashboard, click on Auth from side menu and SIGN-IN-METHOD inside tab bar.
You need to enable anonymous authentication.

Step 2 - Signin Function

We can use signInAnonymously() method for this authentication.

Example

firebase.auth().signInAnonymously()
.then(function() {
   console.log('Logged in as Anonymous!')
   }).catch(function(error) {
   var errorCode = error.code;
   var errorMessage = error.message;
   console.log(errorCode);
   console.log(errorMessage);
});

 

Firebase - Offline Capabilities

In this chapter we will show you how to handle Firebase connection state.

Check Connection

We can check for connection value using the following code.

index.js

var connectedRef = firebase.database().ref(".info/connected");

connectedRef.on("value", function(snap) {
   if (snap.val() === true) {
      alert("connected");
   } else {
      alert("not connected");
   }
});
When we run the app, the pop up will inform us about the connection.
Firebase Offline Popup
By using the function above you can keep track of connection state and update your app accordingly.

 

Firebase - Security

Security in Firebase is handled by setting JSON like object inside security rules.
Security rules can be found when we click on Database inside side menu and then RULES in tab bar.
In this chapter we will go through couple of simple examples to show you how to secure Firebase data.

Read and Write

Next code snippet defined inside Firebase security rules will allow writing access to /users/'$uid'/ for authenticated user with the same uid, but everyone could read it.

Example

{
   "rules": {
      "users": {
         "$uid": {
            ".write": "$uid === auth.uid",
            ".read": true
         }
      }
   }
}

Validate

We can enforce data to string by using the following example.

Example

{
   "rules": {
      "foo": {
         ".validate": "newData.isString()"
      }
   }
}
This chapter only grabbed the surface of Firebase security rules. The important think is to understand how these rules work so you can combine it inside the app.

 

Firebase - Deploying

In this chapter we will show you how to host your app on Firebase server.
Before we begin, let's just add some text to index.html body tag. In this example we will add −
<h1>WELCOME TO FIREBASE TUTORIALS APP</h1>

Step 1 - Install Firebase Tools

We need to install firebase tools globally in command prompt window.
npm install -g firebase-tools

Step 2 - Initialize Firebase App

First we need to login to Firebase in command prompt.
firebase login
Open root folder of your app in command prompt and run the following −
firebase init
This command will initialize your app.
NOTE − If you used default configuration, public folder will be created and index.html inside this folder will be starting point of your app.
You can copy your app file inside public folder as a workaround.

Step 3 - Deploy Firebase App

This is the last step in this chapter. Run the following command from command prompt to deploy your app.
firebase deploy
After this step the console will log your apps Firebase URL. In our case it is called https://tutorialsfirebase.firebaseapp.com. We can run this link in browser to see our app.
Firebase Deploying