{{announcement.body}}
{{announcement.title}}

How to Integrate React Application Using Firebase

DZone 's Guide to

How to Integrate React Application Using Firebase

Learn how to create a web application using React.js and then add authentication using Firebase,

· Web Dev Zone ·
Free Resource

The world of serverless is growing and when talking about the term serverless, Firebase is a name that comes to the mind of many developers and enterprises. But what is Firebase? We'll discuss what Firebase is, how to authenticate with it, and how to use it in your next React project. Excited? Let’s begin.

Firebase is a Google cloud service that provides backend services for mobile and web applications. It is a widely used option for developers for backend-as-a-service. It has a real-time database service so all the records are instantly updated whenever there are changes in the database.

Since React.js is one of the fastest growing front-end JavaScript technologies supported by a large community, React developers need fast and reliable backend services to make the most out of it. Thus, Firebase is a good choice as it comes with the following advantages:

  1. Multiple ways of authenticating with your application.
  2. It provides the Login Persist where you’ll stay logged in even after refreshing or closing the browser window.   
  3. Third-party provider support  e.g. Google, GitHub, Twitter.
  4. It provides secure ways to authenticate.
  5. Manages user session (users will remain logged in even when the browser or application restarts).

All of this allows us to focus on the user and their data rather than the backend code to maintain the sign in protocols. However, Firebase has a limitation that it is mostly used for small scale applications.

Why is it trending?

In the era of startups, one needs to be fast to. This technology supports the creation of a Minimum Viable Product (MVP) which is a great way to attract funds for your startup. Here, Firebase provides the fast backend environment to build your app.

Is it really needed?

Firebase provides the complete backend environment without writing a single line of server side code. It is easy to setup and run with a wide range of third-party auth providers.

By now you must have understood the basics of what Firebase is, it’s advantages/disadvantages, etc. but how can we implement it? Let’s dig deeper into actually working with Firebase and creating our first Firebase app.

So let us start by first creating an account on the Firebase website. You will see something like this:

a) Click on "Go To Console"


b) Now click on 'Add Project.' After clicking, this will take you to the below page.

c) Enter the Project name and accept the conditions.

d) On the left, you’ll be able to see options like Authentication, Database, Storage, Hosting, Functions, and ML Kit under the “Develop” category. However, we’ll be implementing only “Authentication” in this article. Click on Authentication and you will see something like this.

e) Click on the sign-in method you want to select as your sign-in provider. This is where you’ll be able to find different third-party providers with which to authenticate. Enable Email/Password.

f) Now go back to “users,” click on the 'Add User Button,' and create a user manually. Here, I am using the email with a password combination (uou may use any ID with a password).

g) Now the last thing to do on the firebase side is to Click on Web Setup and copy the configuration to use it on front end for your React web application which will have the information like apiKey, authDomain projectId etc.

Integrating Firebase Into a React Application

Congratulations! You are done with creating your first app on Firebase. It is time to integrate it with React.js.

Must Read: Common mistakes in React Development & how can you avoid them

Now, open your terminal and type the following command:

After hitting npm start, your React application will be up and running on port 3000.

Open your code on your favorite IDE (I am using Visual Studio Code for this).

First thing we are going to do is to install Firebase, and we have a Node npm module to do that.

Open your terminal again and type in:

Now we’ll create a folder inside src (source folder) with a name config and, within that project, we’ll create a new file with the name firebase.js. Now paste the configuration which we copied from our Web Setup inthe Firebase Authentication section into the Firebase file.

We will import the Firebase module on the installed Firebase file.

Code in the firebase.js file:

After creating the configuration to connect our React project with Firebase, we will create two pages: one is the Auth Page/Home Page (the page which will appear when the user gets authenticated) and the Unauth Page/Login Page (the page which will appear when the user is not authenticated).

I have used Bootstrap for this project. We won’t be discussing this here as it is out of the scope of this article. However, you can either leave the Bootstrap classes or can use normal CSS for your design purposes.

On the login page, we will have a form which will accept email id and a password and that has a Submit button.

It’s a simple form for logging in. Here is the source code for it.

import React , {Component} from "react";

import { MDBContainer, MDBRow, MDBCol, MDBInput, MDBBtn,MDBCard } from 'mdbreact';

import firebase from './../config/config';

class Login extends Component {

state = {

    email: '',

    password : ''

  }

login = (e) => {

  firebase.auth().signInWithEmailAndPassword(this.state.email , this.state.password).then((res) => {

      console.log("user at firebase",res)

  }).catch((e)=>{

      console.log("error",e)

  })

}

passwordOn = (e) => {

  let password = e.target.value;

  this.setState({password});

}

emailOn = (e) => {

  let email = e.target.value;

  this.setState({email});

}

submitOn = (e) => {

  this.login(e);

}

nameOn = (e) => {

  let name = e.target.value;

  this.setState({name});

}

confirmEmailOn = (e) => {

  let confirmEmail = e.target.value;

  this.setState({confirmEmail});

}

render(){

  return(

    <MDBContainer >

    <MDBRow style={{"textAlign":"center"}}>

    <MDBCard style = {{"width":"145%",'textAlign':"-webkit-center"}} className = "mt-5">

      <MDBCol md="4" className="col-md-offset-4">

        <form>

          <p className="h5 text-center mb-4" onClick = {()=>this.setState({toggle:!this.state.toggle})}>{this.state.toggle ? <span>LogIn to Your Application</span> : <span>LogIn</span> }</p>

          <span>Type your email</span>

          <div className="grey-text">

            <MDBInput

              icon="envelope"

              group

              type="email"

              validate

              error="wrong"

              success="right"

              onChange = {(e)=>this.emailOn(e)}

            />

          <span>Type your password</span>

            <MDBInput

              icon="lock"

              group

              type="password"

              validate

              onChange = {(e)=>this.passwordOn(e)}

            />

          </div>

          <div className="text-center">

            <MDBBtn onClick = {(e)=>this.submitOn(e)}><span>LogIn</span> </MDBBtn>

          </div>

        </form>

      </MDBCol>

  </MDBCard>

    </MDBRow>

  </MDBContainer>

  )

 }

}
export default Login;

This is also the unauth page so when we login we should be on the Home Page and when we logout we should be on the Login page again.

React.js code

We’ll now create an authListener function which is always called when the authentication state changes. So when a user logs in, this function is called: authListener.

We are calling this within the componentDidMount lifecycle:

On the home page, we will have a button that will allow users to logout. For logout, Firebase provides a function, firebase.auth().signOut(). We will be using it as simple function which gets triggered on clicking the logout button:

Here's the home.js file:

React.js code

With all these things in place, you will be able to create a Authenticated Login/Logout Page with Firebase for your React project.

Topics:
web dev ,firebase tutorial ,react.js tutorial ,web application security ,authentication

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}