Firebase
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 player’s 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 player’s 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
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
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
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