Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Serverless Web Applications with React and Firebase
Serverless Web Applications with React and Firebase

Serverless Web Applications with React and Firebase: Develop real-time applications for web and mobile platforms

eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Serverless Web Applications with React and Firebase

Getting Started with Firebase and React

Realtime web applications are said to include the benefits of superfast responses to the user and are highly interactive, which increases the user engagement flow. In this modern web, there are many frameworks and tools that are available to develop Realtime applications. JavaScript is one of the most popular scripting languages that is used for building applications on the web. This book introduces you to ReactJS and Firebase, which you will likely come across as you learn about modern web app development. They both are used for building fast, scalable, and realtime user interfaces that use data and can change over time without reloading the page.

React is famously known as a View in Model-View-Controller (MVC) pattern and can be used with other JavaScript libraries or frameworks in MVC. For managing the data flow in React app, we can use Flux or Redux. In this book, we will also go through how we can implement redux with React and firebase app.

Redux is the alternative to Flux. It shares the same key benefits. Redux works especially well with React, for managing the state of the UI. If you have ever worked with flux, then it's easy too.

Before jumping into the code, let's refresh our knowledge of ReactJS and see what we can do with Firebase and their features, to know the power of firebase.

Here is the list of topics that we'll cover in this section:

  • Introduction of React
  • React Component LifeCycle

This will give you a better understanding of dealing with React Components.

React

React is an open source JavaScript library that provides a view-layer for rendering data as HTML to create interactive UI components. Components have been used typically to render React views that contain additional components specified as custom HTML tags. React views efficiently update and re-render the components without reloading the page when your data changes. It gives you a trivial virtual DOM, powerful views without templates, unidirectional data flow, and explicit mutation. It is a very systematic way of updating the HTML document when the data changes and provides a clean separation of components in a modern, single-page application.

The React Component is built entirely with Javascript, so it's easy to pass rich data through your app. Creating components in React lets you split the UI into reusable and independent pieces, which makes your application component reusable, testable, and makes the separation of concerns easy.

React is only focused on View in MVC, but it also has stateful components that remember everything within this.state. It handles mapping from input to state changes and it renders components. Let's look at React's component life cycle and its different levels.

Component lifecycle

In React, each component has its own lifecycle methods. Every method can be overridden as per your requirements.

When the data changes, React automatically detects the change and re-renders the component. Also, we can catch the errors in the Error Handling phase.

The following image shows the phases of a React Component:

Methods info

Let's take a quick look at the preceding methods.

The constructor() method

The constructor method of React Component gets invoked first when the component is mounted. Here, we can set the state of the component.

Here's an example of constructor in React.Component:

constructor(props) {
super(props);
this.state = {
value: props.initialValue
};
}
Using this.props inside the constructor, we need to call super(props) to access and call functions of parents; otherwise, you will get this.props undefined in the constructor because React sets the .props on the instance from outside immediately after calling constructor, but it will not affect when you are using this.props inside the render method.

The render() method

The render() method is required to render the UI component and examine this.props and this.state and return one of the following types:

  • React elements
  • String and numbers
  • Portals
  • null
  • Booleans

The componentWillMount() method

This method is invoked immediately before componentDidMount. It is triggered before render()method.

The componentDidMount() method

This method is invoked immediately after a component gets the mount. We can use this method to load the data from a remote endpoint to instantiate a network request.

The componentWillReceiveProps() method

This method will be invoked when the mounted component receives new props. This method also allows comparing the current and next values to ensure the changes in props.

The shouldComponentUpdate() method

The shouldComponentUpdate() method is invoked when the component has received the new props and state. The default value is true; if it returns false, React skips the update of the component.

The componentWillUpdate() method

The componentWillUpdate() method is invoked immediately before rendering when a new prop or state is being received. We can use this method to perform an action before the component gets updated.


This method will not be invoked if shouldComponentUpdate() returns false.

The componentDidUpdate() method

The componentDidUpdate() method is invoked immediately when component gets updated. This method is not called for the initial render.

Similar to componentWillUpdate(), this method is also not invoked if shouldComponentUpdate() returns false.

The componentWillUnmount() method

This method is invoked immediately before a React Component is unmounted and destroyed. Here, we can perform any necessary cleanup, such as canceling network requests or cleaning up any subscription that was created in componentDidMount.

The componentDidCatch() method

This method allows us to catch the JavaScript errors in React Components. We can log those errors and display another fallback UI instead of the component tree that crashed.

Now we have a clear idea about component methods that are available in React Components.

Observe the following JavaScript code snippet:

<section>
<h2>My First Example</h2>
</section>
<script>
var root = document.querySelector('section').createShadowRoot();
root.innerHTML = '<style>h2{ color: red; }</style>' +'<h2>Hello World!</h2>';
</script>

Now, observe the following ReactJS code snippet:

var sectionStyle = {
color: 'red'
};
var MyFirstExample = React.createClass({
render: function() {
return (<section><h2 style={sectionStyle}>
Hello World!</h2></section>
)}
})
ReactDOM.render(<MyFirstExample />, renderedNode);

Now, after observing the preceding examples of React and JavaScript, we will have a clear idea of normal HTML encapsulation and ReactJS custom HTML tags.

React isn't an MVC framework; it's a library for building a composable user interface and reusable components. React is used at Facebook in its production stages and instagram.com is entirely built on React.

Firebase

The Firebase platform helps you develop high-quality apps and focus on your users.

Firebase is a mobile and web application development platform backed by Google. It is a one-stop solution for all your needs to develop high-quality mobile and web applications. It includes various products, such as Realtime Database, Crash reporting, Cloud Firestore, Cloud Storage, Cloud functions, Authentication, Hosting, Test lab for Android, and Performance monitoring for iOS, which can be used to develop and test Realtime applications by focusing on the user's needs, rather than the technical complexities.

It also includes products such as Cloud Messaging, Google Analytics, Dynamic Links, Remote Config, Invites, App Indexing, AdMob, and AdWords that help you grow user base and also increase the engagement of your audience.

Firebase provides multiple Firebase services. We can access each service with the Firebase namespace:

  • firebase.auth() - Authentication
  • firebase.storage() - Cloud Storage
  • firebase.database() - Realtime Database
  • firebase.firestore() - Cloud Firestore

We'll cover all the preceding services in the upcoming chapters. In this chapter, we will go through the preceding products/services briefly to get a basic understanding of all features of the Firebase platform. In the upcoming chapters, we will explore web-related products  which can integrate with React platform, in more detail.

Here's the list of topics that we'll cover in this section:

  • Introduction to Firebase and its features
  • List of Firebase Features and how we can use it
  • Cloud Firestore
  • Firebase project setup with JavaScript
  • Sample application "Hello World" with Firebase and JavaScript

As you can see, Firebase offers two types of Cloud Database and Realtime Database, and both support real-time data syncing. We can use both of them in the same application or project. Okay, let's go into detail and learn more about them.

Realtime Database

For any Realtime application, we need a Realtime Database. The Firebase Realtime Database is a cloud-hosted NoSQL database that synchronizes the data in Realtime to every connected client. Instead of a typical request-response model, the Firebase database uses the synchronization mechanism that synchronizes the data to all the connected devices within milliseconds. Another key capability is its offline feature. The Firebase SDK persists the data on the disk; so, even if a user loses their internet connection, the app remains responsive. It automatically synchronizes the data once the connection is reestablished. It is supported by iOS, Android, Web, C++, and Unity platforms. We will cover this in detail in the upcoming chapters.

Firebase Realtime Database can scale around 100,000 concurrent connections and 1,000 writes/second in a single database.

The following screenshot shows the list of features on the left, which are available in Firebase, and we have selected the Realtime Database in the database section. In that section, we have four tabs available:

  • DATA
  • RULES
  • BACKUPS
  • USAGE

Database rules

Firebase database rules are the only way to secure the data. Firebase provides flexibility and expression-based rules language with JavaScript-like syntax to developers to define how your data should be structured, how it should be indexed, and when the user can read and write the data. You can also combine authentication services with this to define who has access to what data and protect your users from unauthorized access. To validate the data, we need to add a rule separately using .validate in the rules.

Consider this example:

{
"rules": {
".write": true,
"ticket": {
// a valid ticket must have attributes "email" and "status"
".validate": "newData.hasChildren(['email', 'status'])",
"status": {
// the value of "status" must be a string and length greater then 0 and less then 10
".validate": "newData.isString() && newData.val().length > 0 && newData.val().length < 10"
},
"email": {
// the value of "email" must valid with "@"
".validate": "newData.val().contains('@')"
}
}
}
}

Here are some other sample blocks of code for applying rules in the Rules tab:

Default: Rule configuration for authentication:

{
"rules": {
".read": "auth != null",
".write": "auth != null"
}}

Public: These rules give full access to everyone, even people who are not users of your app. They give read and write access to your database:

{
"rules": {
".read": true,
".write": true
}}

User: These rules authorize access to a node matching the user's ID from the Firebase authentication token:

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

Private: These rule configs don't allow anyone to read and write to a database:

{
"rules": {
".read": false,
".write": false
}
}
We can also use REST API with Firebase Secret code to write and update Rules for your Firebase app by making a PUT request to the /.settings/rules.json path and it will overwrite the existing rules.

Take, for example, curl -X PUT -d '{ "rules": { ".read": true } }' 'https://docs-examples.firebaseio.com/.settings/rules.json?auth=FIREBASE_SECRET'.

Backups

Firebase allows us to save the daily backup of our database, but that is only available in the Blaze plan. It also applies the security rules automatically to secure your data.

Usage

Firebase allows seeing the usage of the database with the help of an analytical chart. It shows us the connections, storage, downloads, and load in Realtime on our firebase database:

Cloud Firestore

Cloud Firestore is also a cloud-hosted, NoSQL database. You might be thinking that we already have Realtime Database, which is also a NoSQL database, so why do we need Firestore? The answer to this question is that Firestore can be considered as an advanced version of Realtime Database that provides live synchronization and offline support along with efficient data queries. It scales globally and lets you focus on developing apps instead of worrying about server management. It can be used with Android, iOS, and web platforms.

We can use both databases within the same Firebase application or project. Both are NoSQL databases, can store the same types of data, and have client libraries that work in a similar manner.

If you want to try out Cloud Firestore while it's in beta, use our guide to get started:

Once we select the database, it prompts you to apply the security rules before creating the database.

Security rules

Before creating a database and collection in Cloud Firestore, it prompts you to apply the security rules for our database.

Take a look at the following screenshot:

Here are some code example of Firestore rules:

Public:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
Users:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
}
}
Private:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}

Difference between Realtime Database and Cloud Firestore

We have seen that both Realtime Database and Cloud Firestore are NoSQL Databases with Realtime capabilities of syncing the data. So, let's see the difference between both of them based on the features.

Data model

Both databases are cloud-hosted, NoSQL databases, but the data model of both databases is different:

Realtime Database Cloud Firestore
  • Simple data is very easy to store.
  • Complex, hierarchical data is harder to organize at scale.
  • Simple data is easy to store in documents, which are very similar to JSON.
  • Complex and hierarchical data is easier to organize at scale, using subcollections within documents.
  • Requires less denormalization and data flattening.

Real-time and offline support

Both have mobile-first, Realtime SDKs, and both support local data storage for offline-ready apps:

Realtime Database Cloud Firestore
Offline support for mobile clients on iOS and Android only. Offline support for iOS, Android, and web clients.

Querying

Retrieve, sort, and filter data from either database through queries:

Realtime Database Cloud Firestore
Deep queries with limited sorting and filtering functionality:
  • You can only sort or filter on a property, not sort and filter on a property, in a single query.
  • Queries are deep by default. They always return the entire subtree.
Indexed queries with compound sorting and filtering:
  • You can chain filters and combine filtering and sort on a property in a single query.
  • Write shallow queries for sub collections; you can query subcollections within a document instead of an entire collection, or even an entire document.
  • Queries are indexed by default. Query performance is proportional to the size of your result set, not your dataset.

Reliability and performance

When we choose the database for our project, then reliability and performance are the most important parts that come to our mind:

Realtime Database Cloud Firestore
Realtime Database is a mature product:
  • Stability you'd expect from a battle-tested, tried-and-true product.
  • Very low latency, so it's a great option for frequent state-syncing.
  • Databases are limited to zonal availability in a single region.
Cloud Firestore is currently in beta:
  • Stability in a beta product is not always the same as that of a fully launched product.
  • Houses your data across multiple data centers in distinct regions, ensuring global scalability, and strong reliability.
  • When Cloud Firestore graduates from beta, it will have stronger reliability than Realtime Database.

Scalability

When we develop a large-scale application, we must know how much we can scale our database:

Realtime Database Cloud Firestore
Scaling requires sharding:

Scale to around 100,000 concurrent connections and 1,000 writes/second in a single database. Scaling beyond that requires sharing your data across multiple databases.

Scaling will be automatic:

Scales completely automatically (after beta), which means that you don't need to share your data across multiple instances.

Security

As per the security concern, every database has a different way of securing data from unauthorized users:

Source: https://firebase.google.com/docs/firestore/rtdb-vs-firestore?authuser=0.

Realtime Database Cloud Firestore
Cascading rules that require separate validation.
  • Firebase Database Rules are the only security option.
  • Read and write rules cascade.
  • You need to validate data separately using .validate in the rule.
Simpler, more powerful security for mobile, web, and server SDKs.
  • Mobile and web SDKs use Cloud Firestore Security Rules, and server SDKs use Identity and Access Management (IAM).
  • Rules don't cascade unless you use a wildcard.
  • Data validation happens automatically.
  • Rules can constrain queries; if a query's results might contain data the user doesn't have access to, the entire query fails.

As of now, Cloud Firestore is available in beta version; so, in this book, we are only focusing on Realtime Database.

Crash reporting

Crash reporting services help you diagnose problems in your Android and iOS mobile apps. It produces detailed reports of bugs and crashes and also sends them to the configured email address for quick notifications of the problems. It also provides a rich dashboard where you can monitor the overall health of your apps.

Authentication

Firebase Authentication provides a simple and secure solution to manage user authentication for your mobile and web apps. It offers multiple methods to authenticate, including traditional form-based authentication using email and password, third-party providers such as Facebook or Twitter, and using your existing account system directly.

FirebaseUI authentication for web

Firebase UI is completely open source and easily customizes to fit in with your app that includes some set of libraries. It allows you to quickly connect UI elements to the Firebase database for data storage, allowing views to be updated in Realtime, and it also provides the simple interfaces for common tasks such as displaying lists or collections of items.

FirebaseUI Auth is a recommended way to add authentication in Firebase app, or we can do it manually with Firebase Authentication SDK. It allows users to add a complete UI flow for signing in with email and passwords, phone numbers, and with most popular identity providers, including Google and Facebook Login.

FirebaseUI is available at https://opensource.google.com/projects/firebaseui.

We will explore more about Authentication in detail in the upcoming chapters.

Cloud Functions

Cloud Functions allow you to have serverless apps; you can run your custom application backend logic without a server. Your custom functions can be executed on specific events that can be emitted by integrating the following Firebase products:

  • Cloud Firestore triggers
  • Realtime Database triggers
  • Firebase Authentication triggers
  • Google Analytics for Firebase triggers
  • Cloud Storage triggers
  • Cloud Pub/Sub triggers
  • HTTP Triggers

How does it work?

Once you write and deploy a function, Google's servers start listening to those functions immediately, that is listening for events and running the function when it gets triggered. As the load of your app increases or decreases, it responds by rapidly scaling the number of virtual server instances needed to run your function faster. If the function is deleted, idle, or updated by you, then instances are cleaned up and replaced by new instances. In the case of deletion, it also removes the connection between functions and the event provider.

Given here are the events that are supported by Cloud Functions:

  • onWrite(): It triggers when data is created, destroyed, or changed in the Realtime Database
  • onCreate(): It triggers when new data is created in the Realtime Database
  • onUpdate(): It triggers when data is updated in the Realtime Database
  • onDelete(): It triggers when data is deleted from the Realtime Database

Here's a code sample of the cloud function makeUppercase:

exports.makeUppercase = functions.database.ref('/messages/{pushId}/original')
.onWrite(event => {
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
console.log('Uppercasing', event.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return event.data.ref.parent.child('uppercase').set(uppercase);
});
After you write the cloud function, we can also test and monitor our functions.

Cloud Storage

Any mobile or web app will need a storage space that stores user-generated content such as documents, photos, or videos in a secure manner and scales well. Cloud Storage is designed with the same requirement in mind and helps you easily store and serve user-generated content. It provides a robust streaming mechanism for a best end-user experience.

Here's how we can configure Firebase Cloud Storage:

// Configuration for your app
// TODO: Replace with your project's config object
var config = {
apiKey: '<your-api-key>',
authDomain: '<your-auth-domain>',
databaseURL: '<your-database-url>',
storageBucket: '<your-storage-bucket>'
};
firebase.initializeApp(config);
// Get a reference to the storage service
var storage = firebase.storage();
// Points to the root reference
var storageRef = storage.ref();

// Points to 'images'
var imagesRef = storageRef.child('images');

// Points to 'images/sprite.jpg'
// Note that you can use variables to create child values
var fileName = 'sprite.jpg';
var spaceRef = imagesRef.child(fileName);

// File path is 'images/sprite.jpg'
var path = spaceRef.fullPath

// File name is 'sprite.jpg'
var name = spaceRef.name

// Points to 'images'
var imagesRef = spaceRef.parent;
The total length of reference.fullPath must be between 1 and 1,024 bytes, with no Carriage Return or Line Feed characters.
Avoid using #, [, ], *, or ?, as these do not work well with other tools such as Firebase Realtime Database.

Hosting

Firebase provides a hosting service where you can easily deploy your web apps and static content with a simple command. Your web content will be deployed on a global delivery network (GDN), so it will be delivered fast regardless of end-user location. It provides a free SSL for your domain to serve the content over a secure connection. It also provides full versioning and releases management with one-click rollbacks.

Test lab for Android

We test our Android app with a variety of devices running on different Android API versions to ensure that the end user can use our app with any Android device without any issues. However, it is not always possible to make all the different devices available to the testing team. To overcome such problems, we can use Test Lab, which provides cloudhosted infrastructure to test the apps with a variety of devices. It also makes it easy to collect test results with logs, videos, and screenshots. It also tests your app automatically to identify any possible crashes.

Performance Monitoring

Firebase Performance Monitoring is specifically designed for iOS apps' performance testing. You can easily identify the performance bottlenecks of your app with performance traces. It also provides an automated environment to monitor HTTP requests, which helps identify network issues. Performance traces and network data gives better insights on how your app is performing.

The following category of products is used in terms of increasing your user base and also engaging them in a better way.

Google Analytics

Google Analytics is a very well-known product and I think no developer needs its introduction. Google Analytics for Firebase is a free analytics solution to measure the user engagement with your app. It also provides insights on app usage. Analytics reports help you understand the user behavior and hence better decisions can be made regarding app marketing and performance optimizations. You can generate reports based on different parameters, such as device types, custom events, user location, and other properties. Analytics can be configured for Android, iOS, and C++ and Unity apps.

Cloud Messaging

Any Realtime app needs to send Realtime notifications. Firebase Cloud Messaging (FCM) provides a platform that helps you send the messages and notifications to the app user in Realtime. You can send hundreds of billions of messages per day for free across different platforms: Android, iOS, and web. We can also schedule the message delivery—immediately or in future. Notification messages are integrated with Firebase Analytics, so no coding is required to monitor user engagement.

Service Workers are supported on the following browsers:

  • Chrome: 50+
  • Firefox: 44+
  • Opera Mobile: 37+
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
// Retrieve the Instance ID token for use with FCM.
// ...
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
The FCM SDK is supported only in HTTPS pages because of service workers, which are available only on HTTPS sites.

Dynamic Links

Dynamic Links are URLs that help you redirect users to a specific content location in your mobile app or web application. If a user opens a dynamic link in a Desktop browser, the respective web page will be open, but if a user opens it up in your Android or iOS, the user will be redirected to the respective location in your Android or iOS. In addition, Dynamic Links work across the app; the user will be prompted to install the app if it is not installed yet. Dynamic Links increase the chances of conversion of mobile web users to native app users. Dynamic Links as part of online social networking campaigns also increase app installation and they are free forever.

Remote config

How cool is it to change the color theme of your app without redeploying it on the app store? Yes, it is possible to make on the fly changes to your app through Firebase Remote Config. You can manage the app behavior and appearance through server-side parameters. For example, you can give the certain discount on a specific group of audience based on the region without any redeployment of your app.

Invites

Generally, everybody refers the good apps to their friends and colleagues. We do it by copying and pasting the app links. However, it doesn't always work, due to a number of reasons, for example, the link was for Android, so an iOS user can't open it. Firebase Invites make it very simple to share the content or app referrals via email or SMS. It works with Firebase Dynamic Links to give the users the best experience with their platform. You can associate the Dynamic Links to the content you want to share and Firebase SDK will handle it for you, giving the best user experience to your app users.

App indexing

For any app, it is equally important to get the app installed as well as to retain those users with some engagement. To re-engage the users who have installed your app, App indexing is a way to go. With Google search Integration, your app links will be shown whenever users will search for the content your app provides. Also, App Indexing helps you improve Google search ranking for your app links to show them in top search results and autocompletion.

AdMob

The ultimate goal of the app developer is mostly to monetize it. AdMob helps you monetize your app through in-app advertising. You can have different kinds of ads, such as a banner ad, a video ad, or even a native ad. It allows you to show the ads from AdMob mediation platform or from Google Advertisers. AdMob mediation platform has Ad optimization strategy built to maximize your revenue. You can also see the monetization reports generated by AdMob to define your product strategy.

AdWords

One of the best marketing strategies in today's world is online advertisements. Google AdWords helps you reach the potential customers or app users through ad campaigns. You can link your Google AdWords account to your Firebase project to define the specific target audiences to run your ad campaigns.

Now that we have an understanding of all the products of Firebase platform, we can mix and match these products to solve the common development issues and get the best product out in the market.

Getting started with Firebase

Before we actually use Firebase in our sample app, we have to create our Firebase project through Firebase Console at https://console.firebase.google.com/. Opening this link will redirect you to the Google sign in the page where you will have to log in to your existing Google Account or by creating a new one.

Once you successfully log in to the Firebase console, you will see a dashboard like the following screenshot:

We will create our first project by clicking on the Add project button. Once you click on the Add project button, it will show a pop-up window asking for the name of your project and the country of your organization. I will call it a DemoProject, set country to the United States, and click on the CREATE PROJECT button:

Once the project is created, you are good to go. You will be redirected to the project dashboard where you can configure the products/services you want to use in your project:

Next, we will look at how we can integrate this Firebase project in a web app. Your web app can be any JavaScript Or NodeJS project.

First, we will create an example with plain JavaScript, and then we will move further and include React.

Now you need to create a directory in your system with the name of DemoProject and inside it, you will create a couple of folders named images, css, and js (JavaScript) to make your application manageable. Once you have completed the folder structure, it will look like this:

To integrate our Firebase project to our JavaScript app, we will need a code snippet that has to be added in our JavaScript code. To get it, click on Add Firebase to your web app and note the initialization code it has generated, which should look like the following code:

When we start making an application with ReactJS or plain JavaScript, we need to do some setup, which just involves an HTML page and includes a few files. First, we create a directory (folder) called chapter1. Open it up in any of your code editors. Create a new file called index.html directly inside it and add the following HTML5 Boilerplate code:

  • For example, I have created a folder called DemoProject
  • Create a file called index.html in the folder
  • In your HTML, add the code snippet we copied from Firebase console:
I prefer and recommend that you use Visual Studio code editor for any type of JavaScript application development over the listed text editors because of its vast array of features.

Now, we need to copy the Firebase code snippet into the HTML:

<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<title>Chapter 1</title>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an
<strong>outdated</strong> browser.
Please <a href="http://browsehappy.com/">
upgrade your browser</a> to improve your
experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<p>Hello world! This is HTML5 Boilerplate.</p>
<script src="https://www.gstatic.com/firebasejs/4.6.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "<PROJECT API KEY>",
authDomain: "<PROJECT AUTH DOMAIN>",
databaseURL: "<PROJECT DATABASE AUTH URL>",
projectId: "<PROJECT ID>",
storageBucket: "",
messagingSenderId: "<MESSANGING ID>"
};
firebase.initializeApp(config);
</script>
</body>
</html>

The following shows the data in our database, which we will fetch and display on the UI with JavaScript:

//HTML Code to show the message
<p id="message">Hello world! This is HTML5 Boilerplate.</p>
<script>
//Firebase script to get the value from database and replace the "message".
var messageLabel = document.getElementById('message');
var db = firebase.database();
db.ref().on("value", function(snapshot) {
console.log(snapshot.val());
var object = snapshot.val();
messageLabel.innerHTML = object.chapter1.example;
});
</script>

In the preceding code, we are using the on() method to retrieve the data. It takes the event type as value and then retrieves the snapshot of the data. When we add the val() method to the snapshot, we will get data to show in the messageField.

Let me give you a brief of the available events in Firebase that we can use to read the data.

As for now, in Database rules, we are allowing anyone to read and write the data in the database; otherwise, it shows the permission denied error. Consider this as an example:

{
   "rules": {
      ".read": true,
     ".write": true
    }
}

Firebase events

If you can see the preceding code, we have used the callback function that receives a DataSnapshot, which holds the data of snapshot. A snapshot is a picture of the data at a particular database reference at a single point in time, and if no data exists at the reference's location, the snapshot's value returns null.

value

Recently, we have used this valuable event to read the data from Realtime Database. This event type will be triggered every time the data changes, and the callback function will retrieve all the data including children.

child_added

This event type will be triggered once when we need to retrieve the list of items object and every time when a new object is added to our data as given path. Unlike value, which returns the entire object of that location, this event callback is passed as a snapshot that contains two arguments, which include the new child and previous child data.

For example, if you want to retrieve the data on each new comment added to your post in blogging app, you can use child_added.

child_changed

The child_changed event is triggered when any child object is changed.

child_removed

The child_removed event is triggered when an immediate child is removed. It is typically used in combination with child_added and child_changed. This event callback contains the data for the removed child.

child_moved

The child_moved event is triggered when you're working with ordered data like drag and drop in list items.

Now, let's take quick look at our full code:

<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<title>Chapter 1</title><script src="</span>https://www.gstatic.com/firebasejs/4.6.1/firebase.js"></script>
</head>
<body><!--[if lt IE 8]>
<p class="browserupgrade">You are using an<strong>outdated</strong> browser.Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve yourexperience.
</p>
<![endif]-->
<!-- Add your site or application content here -->
<
p id="message">Hello world! This is HTML5 Boilerplate.</p>
<script>
// Initialize Firebase
var config = {
apiKey: "<PROJECT API KEY>",
authDomain: "<PROJECT AUTH DOMAIN>",
databaseURL: "<PROJECT DATABASE AUTH URL>",
projectId: "<PROJECT ID>",
storageBucket: "",
messagingSenderId: "<MESSANGING ID>"
};
firebase.initializeApp(config);
var messageLabel = document.getElementById('message');
var db = firebase.database();
db.ref().on("value", function(snapshot) {
console.log(snapshot.val());
var object = snapshot.val();
messageLabel.innerHTML = object.chapter1.example;
});</script>
</body>
</html>

Now, open index.html in your browser, and let's look at the result:

In the preceding screen excerpt, we can see the database value on MessageLabel and JavaScript data representation in the browser console.

Let's extend this example further by taking the input value from the user and save those values in the database. Then, using the events, we will display that messages in the browser in Realtime:

As shown here, I have added a child node messages in the database. Now, we will add the form input in our HTML with the Save button and at the bottom, we will display those messages list in Realtime when the user submits.

Here's the HTML Code:

<input type="text" id="messageInput" />
<button type="button" onclick="addData()">Send message</button>
<h2>Messages</h2>
<p id="list">sdfdf</p>

Now, we will create the addData() function to get and save the data to Firebase:

 // Save data to firebase
function addData() {
var message = messageInput.value;
db.ref().child('users').push({
field: message
});
messageInput.value = '';
}

In the next screenshot, I have added some messages to the input text:

Now, we need to display those messages into HTML at the bottom of the messages title:

// Update list of messages when data is added
db.ref().on('child_added', function(snapshot) {
var data = snapshot.val();
console.log("New Message Added", data);
snapshot.forEach(function(childSnap) {
console.log(childSnap.val());
var message = childSnap.val();
messages.innerHTML = '\n' + message.field;
});
});

We have used the child_added event, which means whenever any child is added in the messages on node, we need to take that value and update the messages list.

Now, open your browser and note the output:

That looks great. We are now be able to see the message that users have submitted and our data is also getting updated with the new message in Realtime.

Now, let's take a quick look at how our code looks:

<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<title>Chapter 1</title>
<script src="https://www.gstatic.com/firebasejs/4.6.1/firebase.js"></script>
</head>
<body>
<!-- Add your site or application content here -->
<p id="message">Hello world! This is HTML5 Boilerplate.</p>
<input type="text" id="messageInput" />
<button type="button" onclick="addData()">Send message</button>
<h2>Messages</h2>
<p id="list"></p>
<script>
// Initialize Firebase
var config = {
apiKey: "<PROJECT API KEY>",
authDomain: "<PROJECT AUTH DOMAIN>",
databaseURL: "<PROJECT DATABASE AUTH URL>",
projectId: "<PROJECT ID>",
storageBucket: "",
messagingSenderId: "<MESSANGING ID>"
};
firebase.initializeApp(config);

var messageLabel = document.getElementById('message');
var messageInput = document.getElementById('messageInput');
var messages = document.getElementById('list');
var db = firebase.database();
db.ref().on("value", function(snapshot) {
var object = snapshot.val();
messageLabel.innerHTML = object.chapter1.example;
//console.log(object);
});
// Save data to firebase
function addData() {
var message = messageInput.value;
db.ref().child('messages').push({
field: message
});
messageInput.value = '';
}
// Update results when data is added
db.ref().on('child_added', function(snapshot) {
var data = snapshot.val();
console.log("New Message Added", data);
snapshot.forEach(function(childSnap) {
console.log(childSnap.val());
var message = childSnap.val();
messages.innerHTML = '\n' + message.field;
});
});
</script>
</body>
</html>

Summary

Our simple Hello World application and Hello World examples are looking great and working exactly as they should; so, let's review what we've learned in this chapter.
To begin with, we covered React and Firebase and how easy it is to set up the Firebase account and configuration. We also looked at the difference between Realtime Database and Firestore. Apart from that, we learned how simple it is to initialize Realtime Firebase Database with JavaScript and started building our first Hello World application. The Hello World application that we created demonstrates some of Firebase's basic features, such as the following:

  • About Realtime Database and Firestore
  • Difference between Realtime Database and Firestore
  • Firebase account creation and configuration with JavaScript App
  • Firebase Events (value and child_data)
  • Saving the values into the database
  • Read the values from the database

In Chapter 2Integrate React App with Firebase, let's build a React application with Firebase. We will explore some more React and Firebase fundamentals and introduce the project that we will build over the course of this book.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • 1) A practical guide covering the full stack for web development with React 16 and Firebase
  • 2) Leverage the power of Firebase Cloud Storage, messaging, functions, OAuth, and database security to develop serverless web applications.
  • 3) Develop high-performance applications without the hassle of setting up complex web infrastructure.

Description

ReactJS is a wonderful framework for UI development. Firebase as a backend with React is a great choice as it is easy, powerful, and provides great developer experience. It removes a lot of boilerplate code from your app and allows you to focus on your app to get it out quickly to users. Firebase with React is also a good choice for Most Viable Product (MVP) development. This book provides more practical insights rather than just theoretical concepts and includes basic to advanced examples – from hello world to a real-time seat booking app and Helpdesk application This book will cover the essentials of Firebase and React.js and will take you on a fast-paced journey through building real-time applications with Firebase features such as Cloud Storage, Cloud Function, Hosting and the Realtime Database. We will learn how to secure our application by using Firebase authentication and database security rules. We will leverage the power of Redux to organize data in the front-end, since Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. Towards the end of the book you will have improved your React skills by realizing the potential of Firebase to create real-time serverless web applications.

Who is this book for?

This book is for JavaScript developers who have some previous knowledge of React and want to develop serverless, full-stack applications but without the hassle of setting up a complex infrastructure.

What you will learn

  • •Install powerful React.js and Firebase tools to make development much more efficient
  • •Create React components with Firebase to save and retrieve the data in real-time
  • •Use Firebase Authentication to make your React user interface secure
  • •Develop React and Firebase applications with Redux integration
  • •Firebase database security rules
  • •Firebase Cloud Storage Integration to upload and store data on the cloud
  • •Create a complete real-time application with React and firebase
  • •Using Firebase Cloud messaging and Cloud functions with React
  • •Firebase Cloud Storage integration with React
Estimated delivery fee Deliver to Italy

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 10, 2018
Length: 284 pages
Edition : 1st
Language : English
ISBN-13 : 9781788477413
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Italy

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Apr 10, 2018
Length: 284 pages
Edition : 1st
Language : English
ISBN-13 : 9781788477413
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 111.97
Building Serverless Applications with Python
€41.99
Serverless Web Applications with React and Firebase
€32.99
Serverless Design Patterns and Best Practices
€36.99
Total 111.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Getting Started with Firebase and React Chevron down icon Chevron up icon
Integrate React App with Firebase Chevron down icon Chevron up icon
Authentication with Firebase Chevron down icon Chevron up icon
Connecting React to Redux and Firebase Chevron down icon Chevron up icon
User Profile and Access Management Chevron down icon Chevron up icon
Firebase Security and Rules Chevron down icon Chevron up icon
Using Firebase Cloud Messaging and Cloud Functions with React Chevron down icon Chevron up icon
Firebase Cloud Storage Chevron down icon Chevron up icon
Best Practices Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.5
(4 Ratings)
5 star 25%
4 star 50%
3 star 0%
2 star 0%
1 star 25%
bishok limbu Mar 08, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is great for beginners who want to understand more about web applications. I highly recommend this book !!!
Amazon Verified review Amazon
Nayan jyoti talukdar Mar 04, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Very simple written. Easy to understand for the beginners and intermediate level developers.
Amazon Verified review Amazon
Shruthi J Jan 27, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book helped me understand the basics of both Firebase and React.js and also helped me with building all the real time apps. Definetly recommend it to all the javascript developers out there who have knowledge around React.
Amazon Verified review Amazon
I. Pedersen Jul 13, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Very poorly written. A complete waste of time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela