React Firebase

Learn via video courses
Topics Covered

Overview

The important aspect of a dynamic website is a real-time and reliable database. Firebase provides a real-time database, authentication, and cloud storage for applications of different platforms. We can use Firebase with we react frontend to create chat applications and any other real-time dynamic applications.

Introduction

Firebase is a backend service provided by Google to develop Android, IOS, and web applications. We can create a react application with Firebase as a database and authentication provider and monitor the application for stability and crashes. Firebase also provides features for testing, analytics, push notifications, automatic functions, and much more to ease our development lifecycle. The major services of Firebase that we will be dealing with in this article are as follows,

  • Firebase firestore:
    is a NoSQL database that provides storing and querying of unstructured data. Firestore provides the feature to synchronize the data across all the devices in real-time and could scale globally according to the demand. We can also add security rules and secure data based on declarative security language.
  • Cloud Storage:
    is an object storage that is used for storing photos and videos. This service is also scalable and provides robust operations.
  • The Firebase authentication could be used to add a login and SignUp system to our application. We can manage all user data using Firebase and also allow login using different third-party services like Google, Twitter, Github, etc...
  • Firebase functions:
    provides serverless systems that run code based on triggers or HTTPS requests. It is very easy to create a function and manage the function.

Modules

The Firebase modules are different components of the Firebase API that could be used to interact with the services or React Firebase from the front end of React application.

To install the Firebase API in our application, we can use the following command based on the NPM and yarn package manager respectively,

The following services could be used from this package,

  • Firebase Realtime Database to store and sync content.
  • Firebase Auth for secure login and registrations.
  • Firebase Data Generator which is used to generate data in Firebase.
  • Firestore Data Generator which is used to create data in firestore.
  • Linked JSON Data Generator that is used in real-time NOSQL databases.

The following packages also should be installed to use the Firebase API for authentication and also access the database using react components,

After installation of the packages, we will need to set up a project in firebase website. After creating a project, we can view the Firebase dashboard for the project, and on the left side of the dashboard we can see the different services provided by Firebase, then we should enable Authentication, Cloud Storage, and firestore database.

Sandboxes

A sandbox is an environment for the testing and development of applications. In this section, we will see coding examples to implement authentication based on email and password or using Google in our React application.

To access the services of Firebase from our React application, we will need to add some configurations to our firebase react app. We will need to create a config.js file in the base directory of our react application along with a .env file. The .env file is used to store all the required credentials for the database and the config.js file is used to give the credentials to the react firebase API for access to firebase.

The .env file has the following values,

The config.js file is used to create the required Firebase configuration object and create initialize a Firebase app that holds all the configurations to interact with Firebase,

Auth

We need to enable email and password based signIn in the Authentication section of the Firebase console. We can also have a phone number, email link, anonymous and third party based signIn in Firebase.

The following code illustrates a simple SigIn form implemented using Firebase,

Code: Login with email and password

The getAuth() method is used to get the authentication object based on the credentials present in the app object which is then passed to the signIn method along with email and password. The refreshToken is stored in local storage for skipping consecutive login from the same machine until a logout is performed or the token expires.

The email-based signIn feature can be enabled by clicking the Add new provider button in the Authentication section of the Firebase project console. After enabling email-based login, you can see the Email/password option under providers,

react-firebase-1

We can use the sessionStorage.getItem('Auth Token') method to retrieve the token from local storage. If the token is present, we can skip the login and send the user to the home page directly. This is used in the Remember ME feature of login systems.

Anonymous/Google Auth

Anonymous login or guest login could be used in Firebase with react for guest logins and Google auth for Google-based logins. Since the sandbox is a testing environment, we can check the security mechanisms, before moving to production.

Code: Google-based login

Explanation:

  • The FirebaseAuthProvider is a high-level component that passes the authentication details like the current status of the user, user details, etc.. to the FirebaseAuthConsumer component.
  • The signInWithPopup method opens a pop-up for google based signIn, we can also redirect the user for Google based sign-in using the signInWithRedirect method.
  • The stringify function is used to create a string from json object with 2 spaces between each value.
  • The providerId is the provider for the type of login that is performed. For example, the provider id for Google is google.com and for password-based login is password.
  • The IfFirebaseAuthed and IfFirebaseAuthedAnd are rendered on screen only if the user is authenticated through Firebase. The filter props are used to get the required login details from firebase.

react-firebase-2

After singIn with Google, the provider id changes to google.com, and the value of user in the object changes from null to an object provided by Google with tokens and data of the user with fields like uid, Display name etc... A sample user object that is returned after a successful google login is performed is given below,

The authDomain is a domain created by Firebase to handle all auth operations. We can also set up our custom auth domain for authentication. The stsTokenManager provides refresh tokens that will expire in one hour. These refresh tokens could be used to request access tokens that are used for login.

There are usually data that should be shown to the user and data that should only be stored in the database. The sandbox is a testing environment that is perfect for checking these kinds of security constraints.

Realtime Database

The real-time database is an efficient and low-latency database. We can access the data in the database using the FirebaseDatabaseNode component from the @react-firebase/database package.

Infinite List

An infinite list is used to display all the collections based on the path in the Firebase real-time database. You can find the path in the data section of the real-time database. We will discuss the main part of the code that will be rendered on the screen along with imports,

Code: Get data

The FirebaseDatabaseNode component gets the data from the real-time database based on the provided path. The limitToFirst prop is used to specify the number of key-value pairs to be retrieved and the orderByKey prop is used to sort based on the key.

react-firebase-3

Mutation

Mutations in the real-time database involve deleting, updating, and inserting data at runtime using the react Firebase API. The FirebaseDatabaseMutation component is used to perform this function.

Code: Insert data

The FirebaseDatabaseMutation component is used to run mutations based on the path of the real-time database. The type of mutation is defined by the type prop which could be any of push, update, and set. The ServerValue object provided by firebase could be used to access the available values of the real-time database server. The runMutation is a function provided by the FirebaseDatabaseMutation component which has to be invoked with the document to be added as a parameter to add the document in the database. For deleting a document, the path has to be specified along with the key for the document, the type should be set and the runMutation function could be invoked with null as its parameter.

react-firebase-4

In the above example, I have used the FirebaseDatabaseNode component to display the created document.

Transaction

A transaction represents a series of read and writes operations performed with the react firebase real-time database. A single transaction could write to a maximum of 500 documents and we could also increase the limit.

Code:

The FirebaseDatabaseTransaction component is used to run transactions based on the path of the real-time database. The above example creates a simple counter that can be incremented by multiple persons at the same time. The reducer is used to initialize and access the value data in the database. A transaction can be terminated using the return statement. The runTransaction returns a promise which can be chained to mark the end of the transaction.

react-firebase-5

Server Rendered Firebase Data with Auth & Database with Queries

Server-side rendering(SSR) is a technique in which the complete content of the website is rendered on the servers and sent to the browser. This reduces the loading time of the website and provides better accessibility. Frameworks like NextJS and gatsby could be used to implement server side rendering with react firebase.

We can achieve server rendering with react firebase by using features like background triggers, callable functions, authenticated HTTP endpoints, cookie-based authentication, and using dynamic framework support.

Installation

In the above sections, we have covered the @react-firebase package which is a wrapper library built over the official firebase library. To create a simple application with a react frontend and a backend that interacts with Firebase, we can use the default firebase library. The @react-firebase could be used to perform all operations regarding the firebase in the front end easily. Therefore, the installation of a library highly depends on the use case.

Web

The implementation of various services like authentication, storage, etc.. of react Firebase using the official firebase API over web applications is discussed in this section.

Firebase Auth

An important feature of an application is to provide simple and secure registration features. The following simplified code could be used to register a user on Firebase with react,

The createUserWithEmailAndPassword method creates the user and the created user could be viewed in the authentication section on Firebase. The method returns the created user details.

Firebase Realtime Database

We can use the firebase library to connect our react application with the database. The getDatabase method is used to get the database object which will be used to interact with our react firebase database.

The onValue function is used to read data from the database based on the given path. The onValue method is called whenever the data in Firebase is changed. We read the static snapshots at the time of calling the functions and the val method is used to retrieve the data from the snapshot. The ref method is used to create a reference instance of the specified data node. The Object.values() method gets ignores the keys and get all the values from the JSON object.

The react Firebase application uses the onValue method on the useEffect clean-up section because it is an unsubscribe method. Through this, we can prevent memory leaks by closing the connection after the job is done.

Conclusion

  • Firebase is a backend service provider that can be used to develop mobile and web applications.
  • Firebase provides authentication, user management, NOSQL databases, notifications support, and also many features for testing and monitoring an application.
  • The @react-firebase library could be used to use Firebase with react framework as components.
  • The firebase API provides multiple custom login and third-party login options.
  • We can also use features like cookie-based authentication, authenticated HTTP endpoints, etc.. to perform server-side rendering.
  • Firebase database is a robust and scalable database that can be used easily with react applications.