Firebase Tutorial
Firebase Tutorial
This is an introductory tutorial, which covers the basics of the Firebase platform and
explains how to deal with its various components and sub-components.
Audience
This tutorial is directed towards developers in need for a simple, user-friendly backend
platform. After you finish this tutorial, you will be familiar with the Firebase Web Platform.
You can also use this as a reference in your future development.
This tutorial is intended to make you comfortable in getting started with the Firebase
backend platform and its various functions.
Prerequisites
You will need some JavaScript knowledge to be able to follow this tutorial. Knowledge
about some backend platform is not necessary, but it could help you to understand the
various Firebase concepts.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]
i
Firebase
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Set ........................................................................................................................................................... 8
Update .................................................................................................................................................... 9
ii
Firebase
Sign In ................................................................................................................................................... 28
Signout .................................................................................................................................................. 28
iii
Firebase
1. Firebase Overview
Firebase can power your app's backend, including data storage, user authentication, static
hosting, and more. Focus on creating extraordinary user experiences. We will 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
Real-time Database Firebase supports JSON data and all users connected to it
receive live updates after every change.
Firebase Advantages
It is simple and user friendly. No need for complicated configuration.
The data is real-time, which means that every change will automatically update
connected clients.
Firebase Limitations
Firebase free plan is limited to 50 Connections and 100 MB of storage.
1
Firebase
2. Firebase Environment Setup
In this chapter, we will show you how to add Firebase to the existing application. We will
need NodeJS. Check the link from the following table, if you do not have it already.
2
Firebase
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>
3
Firebase
3. Firebase Data
The Firebase data is representing JSON objects. If you open your app from Firebase
dashboard, you can add data manually by clicking on the + sign.
We will create a simple data structure. You can check the image below.
In the previous chapter, we connected Firebase to our app. Now, we can log Firebase to
the console.
console.log(firebase)
4
Firebase
console.log(ref);
5
Firebase
4. Firebase Arrays
This chapter will explain the Firebase representation of arrays. We will use the same data
from the previous chapter.
We could create this data by sending the following JSON tree to the players collection.
['john', 'amanda']
This is because Firebase does not support Arrays directly, but it creates a 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 a
couple of users were to manipulate arrays at the same time, the 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 john and amanda would still have the key (index) 1.
6
Firebase
7
Firebase
5. 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 a specified path. Let us create a reference
to the players collection and set two players.
playersRef.set({
John: {
number: 1,
age: 30
},
Amanda: {
number: 2,
age: 20
}
});
8
Firebase
Update
We can update the Firebase data in a similar fashion. Notice how we are using the
players/john path.
johnRef.update({
"number": 10
});
9
Firebase
When we refresh our app, we can see that the Firebase data is updating.
10
Firebase
6. Firebase Write List Data
In our last chapter, we showed you how to write data in Firebase. Sometimes you need to
have a unique identifier for your data. When you want to create unique identifiers for your
data, you need to use the push method instead of the set method.
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.
11
Firebase
12
Firebase
7. Firebase Write Transactional Data
Transactional data is used when you need to return some data from the database then
make some calculation with it and store it back.
We want to retrieve property, add one year of age and return it back to Firebase.
The amandaRef is retrieving the age from the collection and then we can use the
transaction method. We will get the current age, add one year and update the collection.
13
Firebase
amandaAgeRef.transaction(function(currentAge) {
return currentAge + 1;
});
If we run this code, we can see that the age value is updated to 21.
14
Firebase
8. 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.
We can use the on() method to retrieve data. This method is taking the event type as
"value" and then retrieves the snapshot of the data. When we add val() method to the
snapshot, we will get the JavaScript representation of the data.
Example
Let us consider the following example.
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
15
Firebase
If we run the following code, our console will show the data.
In our next chapter, we will explain other event types that you can use for reading data.
16
Firebase
9. Firebase Event Types
Firebase offers several different event types for reading data. Some of the most commonly
used ones are described below.
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 the data
including children.
child_added
This event type will be triggered once for every player and every time a 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
If we add a new player named Bob, we will get the updated data.
17
Firebase
child_changed
This event type is triggered when the data has changed.
Example
playersRef.on("child_changed", function(data) {
var player = data.val();
console.log("The updated player name is " + player.name);
});
child_removed
If we want to get access of deleted data, we can use child_removed event type.
Example
playersRef.on("child_removed", function(data) {
var deletedPlayer = data.val();
console.log(deletedPlayer.name + " has been deleted");
});
18
Firebase
10. Firebase Detaching Callbacks
Example
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");
playersRef.off();
19
Firebase
11. 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 previous chapters.
Order by Child
To order data by name, we can use the following code.
Example
Let us consider the following example.
playersRef.orderByChild("name").on("child_added", function(data) {
console.log(data.val().name);
});
20
Firebase
Order by Key
We can order data by key in a similar fashion.
Example
Let us consider the following example.
playersRef.orderByKey().on("child_added", function(data) {
console.log(data.key);
});
Order by Value
We can also order data by value. Let us add the ratings collection in Firebase.
21
Firebase
Example
Let us consider the following example.
ratingRef.orderByValue().on("value", function(data) {
data.forEach(function(data) {
console.log("The " + data.key + " rating is " + data.val());
});
});
22
Firebase
12. Firebase Filtering Data
limitToFirst method returns the specified number of items beginning from the first
one.
limitToLast method returns a 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
Let us consider the following example.
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 the first player from the first query, and the last player from the
second query.
23
Firebase
Other Filters
We can also use other Firebase filtering methods. The startAt(), endAt() and the
equalTo() can be combined with ordering methods. In our example, we will combine it
with the orderByChild() method.
Example
Let us consider the following example.
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);
});
The 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"
24
Firebase
since we are ending query with this name. The third one will log "John" since we are
searching for a player with that name.
The fourth example is showing how we can combine filters with "age" value. Instead of
string, we are passing the number inside the startAt() method since age is represented
by a number value.
25
Firebase
13. Firebase Best Practices
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.
26
Firebase
14. Firebase Email Authentication
In this chapter, we will show you how to use Firebase Email/Password authentication.
Create user
To authenticate a user, we can use the createUserWithEmailAndPassword (email,
password) method.
Example
Let us consider the following example.
firebase.auth().createUserWithEmailAndPassword(email,
password).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
We can check the Firebase dashboard and see that the user is created.
27
Firebase
Sign In
The Sign-in process is almost the same. We are using the
signInWithEmailAndPassword(email, password) to sign in the user.
Example
Let us consider the following example.
firebase.auth().signInWithEmailAndPassword(email,
password).catch(function(error) {
console.log(error.code);
console.log(error.message);
});
Signout
And finally we can logout the user with the signOut() method.
Example
Let us consider the following example.
firebase.auth().signOut().then(function() {
console.log("Logged out!")
}, function(error) {
console.log(error.code);
console.log(error.message);
});
28
Firebase
15. Firebase Google Authentication
In this chapter, we will show you how to set up Google authentication in Firebase.
Now you can choose Google from the list, enable it and save it.
index.html
Example
Let us consider the following example.
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;
29
Firebase
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 the Google Signin button to trigger the Google
popup. If signing in is successful, the developer console will log in our user.
We can also click on the Google Signout button to logout from the app. The console will
confirm that the logout was successful.
30
Firebase
16. Firebase Facebook Authentication
Choose Facebook Login and it will appear in the side menu. You will find input field Valid
OAuth redirect URIs where you need to copy the OAuth Redirect URI from Firebase.
Example
Let us consider the following 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";
31
Firebase
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
index.html
index.js
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()
32
Firebase
.then(function() {
console.log('Signout successful!')
}, function(error) {
console.log('Signout failed')
});
}
33
Firebase
17. Firebase Twitter Authentication
Then you would need to copy the callback URL and paste it in your Twitter app. You can
find the Callback URL of your Twitter app when you click on the Settings tab.
index.html
index.js
function twitterSignin() {
firebase.auth().signInWithPopup(provider)
.then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
console.log(token)
console.log(user)
34
Firebase
}).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. The console
will confirm that the authentication is successful.
35
Firebase
18. Firebase GitHub Authentication
In this chapter, we will show you how to authenticate users using the GitHub API.
index.html
index.js
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) {
36
Firebase
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 successful.
37
19. Firebase Anonymous Authentication Firebase
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);
});
38
Firebase
20. Firebase Offline Capabilities
In this chapter, we will show you how to handle the Firebase connection state.
Check Connection
We can check for connection value using the following code.
index.js
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.
By using the above given function, you can keep a track of the connection state and update
your app accordingly.
39
Firebase
21. Firebase Security
Security in Firebase is handled by setting the JSON like object inside the security rules.
Security rules can be found when we click on Database inside the side menu and
then RULES in tab bar.
In this chapter, we will go through a couple of simple examples to show you how to secure
the Firebase data.
Example
Let us consider the following 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()"
}
}
}
40
Firebase
This chapter only grabbed the surface of Firebase security rules. The important thing is to
understand how these rules work, so you can combine it inside the app.
41
Firebase
22. Firebase Deploying
In this chapter, we will show you how to host your app on the Firebase server.
Before we begin, let us just add some text to index.html body tag. In this example, we
will add the following text.
firebase login
Open the root folder of your app in the command prompt and run the following
command.
firebase init
NOTE If you have used a default configuration, the public folder will be created and the
index.html inside this folder will be the starting point of your app. You can copy your app
file inside the public folder as a workaround.
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 the browser
to see our app.
42