Serverless Web Applications with React and Firebase - Harmeet Singh - E-Book

Serverless Web Applications with React and Firebase E-Book

Harmeet Singh

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 252

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Serverless Web Applications with React and Firebase

 

 

Develop real-time applications for web and mobile platforms

 

 

 

 

 

 

 

 

 

Harmeet Singh
Mayur Tanna

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Serverless Web Applications with React and Firebase

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Kunal ChaudhariAcquisition Editor: Isha RavalContent Development Editor: Francis CarneiroTechnical Editor: Ralph RosarioCopy Editor: Shaila KusanaleProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jason MonteiroProduction Coordinator: Nilesh Mohite

First published: April 2018

Production reference: 1040418

 

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78847-741-3

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the authors

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.

I am really thankful to my colleague Mayur Tanna, whose support and encouragement led me to write this book and kept me motivated throughout the journey of completing this book. I am really thankful from the core of my heart to my girlfriend, Shina, and my best friends Nikhil Nair and Bhawana Dugar for their immense contribution and guidelines.

 

 

 

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

I would like to thank Harmeet Singh, coauthor of this book and my best friend, for his tremendous support and motivation in making this work possible.
I want to thank my wife, Dr. Purna, my parents Mr. Ratilal and Mrs. Nirmala, my little child Dhyey, and the rest of my family who supported and encouraged me in spite of all the time it took me away from them.

About the reviewer

Tejas Suthar, with more than 10 years of working as a software developer, engineer, and product lead, brings a deep understanding of enterprise software, management, and technical strategy to any project. His specialties include microservices architecture, AWS, real-time systems, Alexa Skill Development, enterprise web apps, scalability, education, and open source software. He mostly works on JavaScript development and specializes in Node.Js development with other cutting-edge technologies and frameworks.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Serverless Web Applications with React and Firebase

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the authors

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Conventions used

Get in touch

Reviews

Getting Started with Firebase and React

React

Component lifecycle

Methods info

The constructor() method

The render() method

The componentWillMount() method

The componentDidMount() method

The componentWillReceiveProps() method

The shouldComponentUpdate() method

The componentWillUpdate() method

The componentDidUpdate() method

The componentWillUnmount() method

The componentDidCatch() method

Firebase

Realtime Database

Database rules

Backups

Usage

Cloud Firestore

Security rules

Difference between Realtime Database and Cloud Firestore

Data model

Real-time and offline support

Querying

Reliability and performance

Scalability

Security

Crash reporting

Authentication

FirebaseUI authentication for web

Cloud Functions

How does it work?

Cloud Storage

Hosting

Test lab for Android

Performance Monitoring

Google Analytics

Cloud Messaging

Dynamic Links

Remote config

Invites

App indexing

AdMob

AdWords

Getting started with Firebase

Firebase events

value

child_added

child_changed

child_removed

child_moved

Summary

Integrate React App with Firebase

Setting up the environment

Installing React

Using React

React components

What is JSX in React?

Advantages of using JSX in React

How to make your code neat and clean

React Form with JSX

Using React-Bootstrap

Add Ticket Form with React-Bootstrap

Firebase with React

Props and state

The Ref attribute

Summary

Authentication with Firebase

React and Firebase setup with Node.Js

Firebase configuration for authentication

Authentication with Facebook

Creating a login form with React for authentication

Authentication with Facebook

Authentication with Google

Handling account exists errors

Managing the Login across Refresh

Authentication with email and password

Supported types of Auth state persistence

Summary

Connecting React to Redux and Firebase

React setup

Integrating Firebase Realtime Database

What is Redux?

Presentational and Container components

Basics of Redux

Actions

Action creators

Reducers

Store

Data flow

Advanced topics in Redux

Seat booking with Redux

Summary

User Profile and Access Management

Setting up Firebase Admin SDK

Firebase CLI

Installation

Firebase Admin Integration

Using the Firebase Admin Auth API with React

Initializing the Admin SDK

Creating and verifying custom token

Custom claims for admin access and security rules

Adding custom claim with Admin SDK

Verifying custom claim with Admin SDK sending the app

How data is structured in a JSON tree

Summary

Firebase Security and Rules

Security risks and prevention

How secure is your Firebase?

Realtime Database Rules Overview

Authentication

Authorization

Data validation

Rule definition and structure

Query-based rules

Data indexing

Backups

Setup

Restoring from backups

Summary

Using Firebase Cloud Messaging and Cloud Functions with React

Firebase Cloud Messaging (FCM)

Key features of FCM

Sending downstream messages

Sending upstream messages

Versatile message targeting

FCM messages

Setup of Firebase for Javascript web app

Installing Firebase and Firebase CLI

Configuring the browser to receive messages

Client app setup to receive notifications

Server setup to send the notifications

Cloud Functions

Key features of Cloud Functions

Seamless integration with other Firebase Products and third-party APIs

No server to maintain

Private and secure

Life cycle of a function

Setup of Firebase SDK for Cloud Functions

Firebase CLI

Initializing the Firebase Cloud project

Deployment and execution of Cloud Function

Triggering Functions

Realtime Database Triggers

Authentication triggers

Cloud Storage Triggers

HTTP Triggers

Cloud Firestore Triggers

Function termination

Summary

Firebase Cloud Storage

Google Cloud Storage

Key features of Google Cloud Storage

Key concepts

Buckets

Objects

Resources

Object immutability

Storage classes

Multi regional storage

Regional storage

Nearline storage

Coldline storage

Standard storage

Life Cycle Management

APIs and tools

Access control

Key features of Cloud Storage for Firebase

How does it work?

Setting up the Cloud Storage

Upload Files

Adding file metadata

Managing uploads and error handling

Downloading files

Deleting files

Google App Engine

Firebase hosting

Deploying your site

Summary

Best Practices

Best practices with Firebase

Writing the data

Avoid nesting data

Flattern data structure

Avoid arrays

Date object

Custom claims

Managing the user session

Enabling offline capabilities in JavaScript

Optimize database performance

Monitor Realtime Database

Improve performance by metric

Connect your app to multiple database instances

Best practices with React and Redux

Use of Redux

Difference between Redux and Flux

Immutable React State

React Routing

JSX components

Semantics / structured syntax

Use of PropType in React component

Benefit of higher-order components

Redux Architecture benefits

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Realtime applications have dominated the field of web applications for years. Real time isn't limited to only displaying data as soon as it's available; it shows its real power when used with interactive experiences, in which users and systems can instantly communicate with one another. With features such as virtual DOM and declarative views, React proves to be a better fit for such Realtime applications. Firebase makes building and rapid-prototyping these kinds of applications simpler by letting you focus on how the application should behave and look, without getting bogged down in the more tedious parts of Realtime development.

This book will cover the Firebase features such as Cloud Storage, Cloud Function, Hosting, and Realtime Database integration with React to develop rich, collaborative, real-time applications using only client-side code. We can also see how we can secure our application using Firebase Authentication and Database Security Rules. We also leverage the power of Redux to organize the data in the frontend. Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. Toward 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.

This book provides more practical insights rather than just theoretical concepts and includes basic to advanced examples—from hello world to a realtime Web Application.

Who this book is for

The idea behind this book is to help developers create real-time serverless applications really faster with React and Firebase. We wrote this book for the developers who want to create Minimum Viable Product (MVP) using Firebase to validate a business idea. This book is designed to provide practical knowledge to developers who have basic to intermediate knowledge of HTML, CSS, React, and JavaScript and want to learn more about React, Redux, and Firebase integration. This book is also aimed at developers who don't want to waste their time searching hundreds of tutorials of React, Redux, and Firebase and have everything in one place with real-life examples to get productive quickly. This book is for anyone interested in learning only Firebase.

Lastly, if you want to develop serverless apps and want to know end to end, from designing to hosting, with step-by-step instructions, this book is for you.

What this book covers

Chapter 1, Getting Started with Firebase and React, introduces the ReactJS and Firebase features and teaches what you can do with them. It gives a brief detail about setting up a Firebase account and create the demo project with JavaScript.

Chapter 2, Integrate React App with Firebase, looks at setting up the React environment and takes a quick look at the JSX and React component methods. It also goes into creating form components in React using JSX and Firebase Realtime Database for our helpdesk application.

Chapter 3, Authentication with Firebase, focuses on starting to flesh out the helpdesk application set up in Chapter 2, Integrate React App with Firebase, by adding a Firebase Authentication to secure the application with login component.

Chapter 4, Connecting React to Redux and Firebase, explores Redux in detail and looks at how and when you need to use Redux in our React app. It will also show you how you can integrate all three—React, Redux, and Firebase—with a sample seat booking application.

Chapter 5, User Profile and Access Management, shows you how you can use Firebase Admin SDK, which provides a user management API to read and write Realtime Database data with full admin privileges by creating application admin page.

Chapter 6, Firebase Security and Rules, demonstrates how you can secure our database by Firebase Realtime database rules, and it briefly looks at the common database security risks and the checklist to prevent such threats.

Chapter 7, Using Firebase Cloud messaging and Cloud functions with React, helps us to send free messages across different platforms: Android, iOS, and web in Realtime. It takes you through how you can run your custom application logic without a server.

Chapter 8, Firebase Cloud Storage, covers how you can integrate Firebase cloud storage into your application and see the features and how you can use it.

Chapter 9, Best Practices, teaches the dos and don'ts when you are creating a web application with react, Firebase, and redux.

To get the most out of this book

You should have basic programming experience with React, HTML, CSS, and JavaScript to read this book profitably. It is assumed that you know already how Node Package Manager (npm) works to install any dependencies, and you have a basic idea about ES6 Syntax.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Serverless-Web-Applications-with-React-and-Firebase. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

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

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