Serverless Web Applications with React and Firebase

5 (1 reviews total)
By Harmeet Singh , Mayur Tanna
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

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.

Publication date:
April 2018
Publisher
Packt
Pages
284
ISBN
9781788477413

 

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

Note

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
 };
 }

Note

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

Note

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.

Note

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.

Note

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.

Note

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

Note

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:

  • Go to the https://console.firebase.google.com/
  • Select your project, DemoProject
  • Click on the Database in the left section navigation and select the Cloud Firestore database:

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.

Note

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);
 });

Note

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;

Note

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);
});

Note

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:

Note

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.

Note

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.

Note

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>
<htmlclass="no-js"lang="">
<head>
<metacharset="utf-8">
<title>Chapter 1</title><scriptsrc="</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 -->
<pid="message">Hello world! This is HTML5 Boilerplate.</p>
<script>
// Initialize Firebase
varconfig={
 apiKey: "<PROJECT API KEY>",
 authDomain: "<PROJECT AUTH DOMAIN>",
 databaseURL: "<PROJECT DATABASE AUTH URL>",
 projectId: "<PROJECT ID>",
 storageBucket: "",
 messagingSenderId: "<MESSANGING ID>"
};
firebase.initializeApp(config);
varmessageLabel=document.getElementById('message');
vardb=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 2, Integrate 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.

About the Authors

  • Harmeet Singh

    Harmeet Singh is a Senior Associate working for Synechron with varied experience in UI. He hails from the holy city of Amritsar, India. His expertise includes HTML5, CSS, JavaScript, jQuery, Angular, ReactJS, Redux, Firebase, MongoDB, and Node.js. His interests include music, sports, and adventure.

    Harmeet has given various presentations and conducted many workshops on UI development. On the academic front, Harmeet is a graduate in IT, and is a GNIIT diploma holder from NIIT, specializing in software engineering.

    He can be reached on Skype and LinkedIn at harmeetsingh090.

    Browse publications by this author
  • Mayur Tanna

    Mayur Tanna is a Senior Big Data Consultant working with CIGNEX Datamatics. He has worked on various high-value projects with international clients such as World Bank and played a key role in creating the architecture of those projects using the latest technologies including React, Angular, Node.js, MongoDB, Spring Boot, Firebase, Amazon Web Services, and Google Cloud Platform.

    He holds a Master's degree in Computer Applications and has trained a lot of engineering students and freshers through tech workshops.

    Browse publications by this author

Latest Reviews

(1 reviews total)
To the point and topical.

Recommended For You

Mastering React Test-Driven Development

Implement TDD for your React applications using Jest, React Router, Redux, and GraphQL/Relay. Learn BDD and end-to-end acceptance testing with CucumberJS and Puppeteer.

By Daniel Irvine
React Design Patterns and Best Practices - Second Edition

Build modular React web apps that are scalable, maintainable and powerful using design patterns and insightful practices

By Carlos Santana Roldán
React Projects

Build cross-platform applications of varying complexity for the web, mobile, and VR devices using React tooling

By Roy Derks
React Native Cookbook - Second Edition

Improve your React Native mobile development skills or transition from web development to mobile development with this practical solution-packed guide

By Dan Ward