0% found this document useful (0 votes)
36 views

Firebase

Uploaded by

Ursu Alex
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Firebase

Uploaded by

Ursu Alex
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Firebase

Table of Contents
About the Tutorial .................................................................................................................................... i

Audience .................................................................................................................................................. i

Prerequisites ............................................................................................................................................ i

Copyright and Disclaimer ......................................................................................................................... i

Table of Contents .................................................................................................................................... ii

1. FIREBASE – OVERVIEW ........................................................................................................ 1

2. FIREBASE – ENVIRONMENT SETUP ...................................................................................... 2

3. FIREBASE – DATA ................................................................................................................. 4

4. FIREBASE – ARRAYS ............................................................................................................. 6

5. FIREBASE – WRITE DATA...................................................................................................... 8

Set ........................................................................................................................................................... 8

Update .................................................................................................................................................... 9

6. FIREBASE – WRITE LIST DATA ............................................................................................ 11

The Push Method .................................................................................................................................. 11

The Key Method .................................................................................................................................... 12

7. FIREBASE – WRITE TRANSACTIONAL DATA ........................................................................ 13

8. FIREBASE – READ DATA ..................................................................................................... 15

9. FIREBASE – EVENT TYPES ................................................................................................... 17

10. FIREBASE – DETACHING CALLBACKS .................................................................................. 19

ii
Firebase

11. FIREBASE – QUERIES .......................................................................................................... 20

Order by Child ....................................................................................................................................... 20

Order by Key ......................................................................................................................................... 21

Order by Value ...................................................................................................................................... 21

12. FIREBASE – FILTERING DATA.............................................................................................. 23

Limit to First and Last ............................................................................................................................ 23

Other Filters .......................................................................................................................................... 24

13. FIREBASE – BEST PRACTICES .............................................................................................. 26

14. FIREBASE – EMAIL AUTHENTICATION ................................................................................ 27

Create user ............................................................................................................................................ 27

Sign In ................................................................................................................................................... 28

Signout .................................................................................................................................................. 28

15. FIREBASE – GOOGLE AUTHENTICATION ............................................................................ 29

16. FIREBASE – FACEBOOK AUTHENTICATION ......................................................................... 31

17. FIREBASE – TWITTER AUTHENTICATION ............................................................................ 34

18. FIREBASE – GITHUB AUTHENTICATION.............................................................................. 36

19. FIREBASE – ANONYMOUS AUTHENTICATION .................................................................... 38

20. FIREBASE – OFFLINE CAPABILITIES..................................................................................... 39

21. FIREBASE – SECURITY ........................................................................................................ 40

Read and Write ..................................................................................................................................... 40

22. FIREBASE – DEPLOYING ..................................................................................................... 42

iii
Firebase
1. 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 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.

 Authentication – We can use anonymous, password or different social


authentications.

 Hosting – The applications 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 real-time, which means that every change will automatically update
connected clients.

 Firebase offers simple control dashboard.

 There are a number of useful services to choose.

Firebase Limitations
 Firebase free plan is limited to 50 Connections and 100 MB of storage.

In the next chapter, we will discuss the environment setup of Firebase.

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.

S No. Software & Description

NodeJS and NPM


1 NodeJS is the platform needed for Firebase development. Checkout
our NodeJS Environment Setup.

Step 1 – Create a Firebase Account


You can create a Firebase account here.

Step 2 – Create Firebase App


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

Step 3a – Create a basic HTML/JS App


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

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>

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

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

We can create a reference to our player’s collection.

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

console.log(ref);

We can see the following result in the console.

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.

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

playersRef.set({
John: {
number: 1,
age: 30
},

Amanda: {
number: 2,
age: 20
}
});

We will see the following result.

8
Firebase

Update
We can update the Firebase data in a similar fashion. Notice how we are using the
players/john path.

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

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.

The Push Method


The push() method will create a unique id when the data is pushed. If we want to create
our players from the previous chapters with a unique id, we could use the code snippet
given 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.

11
Firebase

The Key Method


We can get any key from Firebase by using the 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).

12
Firebase

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.

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.

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

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.

var email = "[email protected]";


var password = "mypassword";

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.

var email = "[email protected]";


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 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.

Read and Write


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

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.

<h1>WELCOME TO FIREBASE TUTORIALS APP</h1>

Step 1 – Install Firebase Tools


We need to install firebase tools globally in the command prompt window.

npm install -g firebase-tools

Step 2 – Initialize the Firebase App


First we need to login to Firebase in the command prompt.

firebase login

Open the root folder of your app in the command prompt and run the following
command.

firebase init

This command will initialize your app.

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.

Step 3 – Deploy Firebase App


This is the last step in this chapter. Run the following command from the 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 the browser
to see our app.

42

You might also like