Two Ways to Authenticate a React App with Firebase

Authentication means allowing access to an application through verified means. This means that a user is barred from accessing an application until they meet specific user requirements. From creating a user with email and password to allowing users to redirect via their Google accounts and so on.

In this article, we are going to look at two ways to authenticate a React application using Firebase.

What is Firebase

Firebase is a Google mobile platform that constitutes backend cloud computing services and application development platforms. This means it can host authentication services.

This drives us to the point of using Firebase for the Google account sign-in redirect. We will also use Firebase to create a user with an email and password in this article.

Prerequisites

  • Working knowledge of HTML, CSS and JavaScript.

  • Beginner Knowledge of React.

  • An ID such as VS Code.

  • A browser such s Firefox or Chrome.

How to get started with Firebase

You first need to log in to Firebase. Click on get started to create a project and you will redirect to a page where you can add your project name.

Image description

Once you finish creating your project you will be directed to the project's main page as shown below.

Image description

From the sidebar, click Build to get the drop-down menu that allows you to select the authentication option. Click on get started to select your authentication providers.

Image description

In your case, you will need to enable Email/Password and Google as that is what you'll need in your React application. Please note: Once you enable one provider you will have to click the Add new provider button to enable the second option.

Once you click the enable button, select the project support email you will use and click save.

Enable the second option and click save.

Back to your project's home page. Choose the web option abbreviated by closing tags web option abbreviated by a closing tag. This will lead you to a page that allows you to create a nickname for your app. Do that and click the Register App button.

This will then direct you to the "Add Firebase to your web app" option. Select the npm option and copy the code snippet provided (you will use this code snippet in your React app soon).

Cloud Firestore is a document database that allows you to store, sync and query data for your mobile and web applications. This is what you'll use to create a database.

On the left navbar click Build and select Firebase database. Select the start in test mode option.

Image description

How to Create React App

To create your React app, open your terminal and run npm create vite@latest

This will prompt you to create a project name, after that choose the React option to create your React application. Proceed to create a JavaScript variant. Follow the other commands to change the directory, and install and run your app.

Now that your React app is running, it's time to install Firebase and React Firebase Hooks. Run the following command in your terminal:

npm install firebase react-firebase-hooks

Remember the code snippet you copied, create a file called firebase.js in your React app and paste the code there. Don't forget to import Firestore and getAuth as shown below.

import { getAuth } from "firebase/auth"; import { getFirestore } from "firebase/firestore";

Then proceed to initialize the imports at the bottom as shown below:

export const auth = getAuth(app);

export const db = getFirestore(app);

export default app;

How to Sign in with Redirect

Now it's time to create our login page and Navbar and implement the authentication. Create a components folder and create a Navbar file in there and paste the following code: You can learn more here about Firebase Authentication for websites.


import React from "react";
import { auth } from "../firebase";
import { useAuthState } from "react-firebase-hooks/auth";
import { GoogleAuthProvider, signInWithRedirect } from "firebase/auth";


const Navbar = () => {

const[user] = useAuthState(auth);

const userSignIn = () => {
    const provider = new GoogleAuthProvider();
    signInWithRedirect(auth, provider)
}
const signOut = () => {
    auth.signOut();
}
 return (

<nav className="nav-bar">
    <h2>React auth</h2>

    { user ? ( <button onClick={signOut} className="sign-out" type ="button">Sign Out</button>
    ): (

           <button onClick={userSignIn} className="sign-in" type= "button">Sign In</button>
   )


  }
</nav>
    )
   }

export default Navbar;

Clear out the App.jsx file contents and replace with:

import React from 'react'; import Navbar from "./components/Navbar";
import {useAuthState } from "react-firebase-hooks/auth";

import { auth } from "./firebase";

function App() {

const [user] = useAuthState(auth);

return (

   <> 
    <Navbar />
   </> 
   ) 
}

export default App;

At this point your Sign in with Redirect is ready. However, if you encounter an unauthorized domain error, head over to your Firebase project, in the authentication tab select settings and add http://127.0.0.1/ as one of the authorized domains. This is if you Vite to create your React app.

How to Create User With Email and Password

Create a components folder to host your files and then proceed to create the Login.jsx file and paste the below code in there.

import React, { useState } from "react";
import '../components/Navbar'
import { auth } from "../firebase";
import { createUserWithEmailAndPassword } from 'firebase/auth';

const Login = () => {


const [email, setEmail] = useState("")
const [password, setPassword] = useState("")

const signOut = () => {
     auth.signOut();
}


const onLogin = (e) => {
    e.preventDefault()
    createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
        const user = userCredential.user;
        console.log(user)
    })
    .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log(errorCode, errorMessage)
    })
}



 return (

<div>


    <form className="form">


        <div className="logincontainer"> 
           <p>Firebase Auth</p>
           <p> Create Account with email & password to login</p>

              { !createUserWithEmailAndPassword ? (<button onClick={signOut} className="sign-out" type ="button">Sign Out
               </button>) : (

        <div className="input-container">

            <input type="email" placeholder="enter your email" onChange={(e)=>setEmail(e.target.value)} required />

            <input type="password" placeholder="enter your password" onChange={(e)=>setPassword(e.target.value)} required />

            <button type="submit" onClick={onLogin}>Login</button>
        </div>)
       }


        </div> 
</form> 




</div>
)
}

export default Login;

To test this section out don't forget to import your Login file into App.jsx.

These two way can work hand in hand in giving users options to choose from in authentication.

Conclusion

Your React authentication is now ready and for every login, you'll be able to access the new user's emails in your Firebase users section under the authentication tab. In this article, you have learnt two ways of authenticating your React app using Firebase. Using the Google sign-in redirect and creating a user with email and password.

Happy Reading!