How to set up Firebase Authentication in React

Best Of

How to set up Firebase Authentication in React

Firebase is an application development platform that supports web and mobile development. It is owned by Google and provides various services like real-time databases, storage, authentication, hosting, and analytics.

Firebase authentication is a managed identity authentication system that lets you store and create user sessions without the need for a backend. Here is a quick tutorial on how to set up Firebase authentication with React.

How Firebase authentication works

01-firebasereact.png

Firebase authentication is part of the services suite offered by Google's full-stack app platform. It covers a majority of authentication options including email, and federated identity providers such as Google, Facebook, Twitter, and GitHub. Firebase authentication is a free service, with the exception of phone verification - which is free for the first 10k API calls.

Authentication works by providing an API that lets valid apps access login statuses and session tokens that are managed by Firebase. It uses OAuth 2.0 standards for security and OpenID Connect for interoperability.

There are multiple ways to implement Firebase authentication, including a 'drop-in' solution where an external user flow is provided to sign in users. Another way is to use the Firebase SDK authentication, which is a package that can be leveraged for backend and native applications.

For this tutorial, we are going to focus on implementing Firebase authentication in a React app.

Implementing Firebase Authentication in a React app

In this tutorial, we will be implementing the following:

  • email and password authentication method
  • Single sign-on with Google authentication method

You wil need to have a basic understand of React before you begin.

Step 1: Create a new Firebase project

02-firebasereact.png

Before we can use authenticated identities through Firebase, you need to create a project. To do this, go to your Firebase console. You should see the screen as per the screenshot below (or something similar).

03-firebasereact.png

Click the Create a Project button, and you will be redirected to the project creation wizard. You will need to enter a project name and enable Google analytics if needed.

It takes a few seconds for your newly minted Firebase project to boot up. Once completed, you will be automatically redirected to your project's dashboard. Your Firebase project's dashboard looks something like this:

Step 2: Enable Firebase Authentication

To enable Firebase Authentication, you need to select the Authentication option from the left side panel. It will redirect you to the Firebase Authentication options, where you can manage users, sign-in options, and templates.

04-firebasereact.png

You can select multiple authentication options from the sign-in method page, including native and federated sign-in methods.

For this tutorial, we will be using Email/Password and Google sign-in. Here is a quick rundown on how to enable email and password, and Google sign-in.

Enabling Email/Password Sign-In

To enable email and password authentication method on Firebase, you need to switch it on by clicking on the enable toggle.

05-firebasereact.png

After saving, you will be redirected back to the sign-in method page, and you will see the Email/Password authentication option in the sign-in provider list.

06-firebasereact.png

Enabling Google Authentication federated profile Sign-in

To enable Google federated sign-in, you need to add another sign-in provider by clicking Add new provider button.

07-firebasereact.png

Select Google from the additional providers and it will open a configuration modal like below:

08-firebasereact.png

To save user details - that is, data that is associated with the user profile - you will need a database. We will be using Firebase's Firestore database for this purpose.

Step 3 — Creating a Cloud Firestore Database

To create a Firestore database, you need to select the Firestore database option from the left panel. The free tier gives a generous 600,00 writes and 1.5 million reads before you start getting charged for usage.

09-firebasereact.png

You will be directed to a database creation wizard. Click on Create database. This will give you the database security permissions. For now, you can grant all access. However, you will need to close up accessibility to only your application to prevent leaks and potential security breaches.

10-firebasereact.png

Make sure to enable write permissions by changing rules to allow read, write: if true.

11-firebasereact.png

After clicking Enable, you will be redirected to the Firestore database page within a few seconds.

12-firebasereact.png

Now that we've got your console set up for Firebase authentication and a database set up, we can now integrate it into our React application. 13-firebasereact.png

Step 4: Registering your React app with Firebase

To connect your Firebase backend to your react app, you need to Firebase project settings and configure it to use the React app. When you go to Firebase settings and scroll down, you will see a message like the below:

14-firebasereact.png Then, you need to select the Web application icon (</>), and it will take you to the app registration page.

15-firebasereact.png

After registering the web application with a nickname, you will get the necessary details to add Firebase SDK to your React application. Make sure to copy these details before completing the wizard since we will be using them in the next step.

16-firebasereact.png

Step 5: Adding Firebase to your React Application

Here is a series of steps you need to follow to add Firebase to your React application.

Installing Firebase

Firebase provides 2 options to install it to our application - NPM and <script> tag. For our React app, we are going to use NPM. Here is how to install the Firebase package as a module via NPM.

npm install firebase

Creating a Firebase service in React

Then we need to create a service file to keep all the firebase configurations and functions.

Here is an example of a service file:

import firebase from “firebase/app”; import { getFirestore, collection, addDoc, where, query, getDocs} from "firebase/firestore"; import "firebase/compat/auth"; const firebaseConfig = { apiKey: “<API_KEY_HERE>”, authDomain: “<AUTH_DOMAIN_HERE>”, projectId: “<PROJECT_ID_HERE>”, storageBucket: “<PROJECT_STORAGE_BUCKET_HERE>”, appId: “<APP_ID_HERE>”, measurementId: “<MEASUREMENT_ID_HERE>”, }; firebase.initializeApp(firebaseConfig); const db = getFirestore(); const provider = new firebase.auth.GoogleAuthProvider(); provider.setCustomParameters({ prompt: 'select_account' }); export const auth = firebase.auth(); export default firebase;

In the below user registration function, Firebase returns a new user when we pass the email and the password to auth.createUserWithEmailAndPassword(email, password) - which is Firebase's auth service method. We will save the records to a Firestore collection using the database service.

// User Registration const userRegistration = async (name, email, password) => { try { const res = await auth.createUserWithEmailAndPassword(email, password); const user = res.user; await db.collection("users").add({ uid: user.uid, name, authProvider: "local", email, }); } catch (err) { alert(err.message); } };

Firebase will take care of the authentication process from there and return the validity of the user.

// Sign-in with Email/Passwordexport const signInWithEmailAndPassword = async (email, password) => { try { await auth.signInWithEmailAndPassword(email, password); } catch (err) { alert(err.message); } };

Firebase provides a password reset option. All you need to do is pass the email to Firebase auth service using sendPasswordResetEmail() method.

export const resetPassword = async (email) => { try { await auth.sendPasswordResetEmail(email); } catch (err) { alert(err.message); } };

For Google sign-in, we need to handle both registration and sign-in in the same function. To prevent duplication, I will check if the users exist in the database, and if not, I will create a new record and continue with the sign-in process.

// Google Sign-in export const signInWithGoogle = async () => { try { const res = await auth.signInWithPopup(provider); const user = res.user; const userRef = collection(db, "users"); const result = await getDocs(query(userRef, where("uid", "==", user.uid))); if (result.empty) { await addDoc(collection(db, "users"), { uid: user.uid, name: user.displayName, authProvider: "google", email: user.email, }); } } catch (err) { alert(err.message); } };

That’s basically it. You don't need to deal with password storage management systems or security protocols that come with managing identities. Firebase has you covered.

Share this post