Create You First Firebase Project in React and implement Google Sign-In Method

Asif Ur Rahman
8 min readMar 29, 2022

--

Hey dear friends, this is Asif Ur Rahman, a Technical Course Writer. Today I am going to show you how you can easily build a Google Sign-In system on your React Application. Let’s get started.

Prerequisites: First of all you will need these prerequisites.

  • Install Node.js on your machine.
  • Then install a basic React App on your machine and run it in your Code Editor. (Here I am using Visual Studio Code)

Creating a Firebase Project: Creating a Firebase project will be done in some simple steps.

  • Go to Firebase Official Website. And create an account.
  • Then somewhere you will see a button namely “Get Started”. Find it and click it. This will take you to the Firebase Console tab. Or you can simply click on the “console” tab menu to do that.
  • Then click on the “Add Project” button to create a new project.
  • Then give the name of your project. Here I am giving a fancy name like “Raw Authentication”.
  • After that, the google authentication process will come. You can enable or disable this google authentication button. I am closing it because it is not a final project. Then continue.
  • After completing the full process click on continue.

🌟 Let’s see some snapshots in this overall process.

( Click on Get Started Button)

( Click on Add Project Button)

( Give a fancy name and continue 😉)

( You can enable or disable this google authentication button. I am closing it because it is not a final project. Then continue)

( After completing the full process continue.)

Yeah, your firebase project is ready now. After completing the upper steps, you will find a wonderful dashboard of your project given below.

🌟 N.B: Click on every tab in this dashboard and see which type of work they can do. In this project, we basically use the “Authentication” tab. But you can use this firebase for many cases like a database.

Now it is time to work in our playground (Code Editor) to integrate this project with our basic React App. Don’t worry. All processes will be described clearly. Let’s do that.

Installing Firebase: At first, you have to install the firebase in your React Application. So open the project folder in your VScode. Open the VScode terminal and install firebase using this npm.

 npm install firebase

Adding the firebaseConfig file: Now it is time to connect our “Raw Authentication” firebase project to our React App. To do this we will need a file named “firebaseConfig.js”. To find it go to your firebase project dashboard. Click on the “web” icon.

Then register your firebase app by writing the name once again. Don’t change another thing just next > next > next > and go to the console. This process basically creates the firebase config file.

Now go to the project settings from the project overview tab. Stay in the “General” tab and scroll down. And near the end of this page, you will find three tabs namely “npm, CDN, config”. Click on the config tab and copy the codes.

Then create a file namely firebase.config.js ( you can give a name of your choice) and paste this code. Then export it using the “export” keyword before the “const” keyword.

Authentication Process with Google Sign-In method: Now is the time for the authentication process. We will complete it in some simple steps.

On the Google Authentication: Go to the firebase project dashboard again. Click on the “Authentication” tab > Google Sign In > Enable it.

Initializing firebase: First of all, we have to initialize firebase in our project. Here I am working on the App.js file. But you will do all the firebase authentication processes in your “Log In” file. As this is a simple project and there is no special “Login” file so we will add all code in our App.js file. Anyway, you can initialize firebase by importing it like below.

import { initializeApp } from ‘firebase/app’;

Importing the firebase config file: Then import the firebase.config.js file in your App.js file and initialize it using the below codes.

import { firebaseConfig } from ‘./firebase.config’;const app = initializeApp(firebaseConfig);

Creating a button: Now we have to create a Sign-In button through which we will be authorized by clicking the button. So insert these below codes in your “App” function/ component.

return (<div className=”App”><button>Sign In</button></div>);

Event Handler: Now add an event handler in the Sign In button for the sign-in process. Here I am giving the event handler as “handleSignIn” so that it can relevant to our work.

<button onClick={handleSignIn}>Sign In</button>

Importing Services from firebase Auth: Now we have to import some services from the firebase authentication. For google Sign-In we will import these below services.

import { getAuth, signInWithPopup, GoogleAuthProvider } from “firebase/auth”;const auth = getAuth();const provider = new GoogleAuthProvider();

Completing the Event Handler: Now it is time for completing the event handler. We will use the below codes in the “App” function to complete it.

const handleSignIn = () => {signInWithPopup(auth, provider).then((result) => {// This gives you a Google Access Token. You can use it to access the Google API.const credential = GoogleAuthProvider.credentialFromResult(result);const token = credential.accessToken;// The signed-in user info.const user = result.user;// …}).catch((error) => {// Handle Errors here.const errorCode = error.code;const errorMessage = error.message;// The email of the user’s account used.const email = error.email;// The AuthCredential type that was used.const credential = GoogleAuthProvider.credentialFromError(error);// …});};

🌟That’s it. After running your React Application in your browser you will find the interface given below.

Just a Sign-In button, right? Yeah. But the codes in the Event Handler tell you that after clicking on the Sign-In button you will be shown a pop-up that is provided by Google. Which is like below.

Now, this is your time. If you successfully enter your Gmail and password you will be authorized.

Surety: But how you will be sure that you are logged in or not? For this, you can show some data in your UI accessing from the authentication process.

Look into the codes of the handleSignIn event handler. It will give you basically a result and error. If you are successfully logged in, you can see your result using the console log. You can also see the error also using the console log.

Show image and name in the UI: But it is better to visualize the data accessed from your Gmail account. For this set a state like the below.

const [user, setUser] = useState({isSignedIn: false,name: ‘’,email: ‘’,photo: ‘’,});

Here we have passed an empty object in the useState() hook of React. Before the authentication, the property value of the object will be empty. Use these below codes to show your name, email, and photo in the UI.

return (<div className=”App”>{user.isSignedIn &&<div><img src={user.photo} alt={user.name} /><br /><h2 style={{fontWeight: ‘bold’}}>Welcome, {user.name}</h2></div>}<button onClick={handleSignIn}>Sign In</button></div>

N.B: Here I have used the ternary operator. It means that your image and name will be shown in the UI only if the values of the user.isSignedIn becomes “true”.

Now write some codes in the handeSignIn event handler like below to fulfill the process.

const handleSignIn = () => {signInWithPopup(auth, provider).then((result) => {const {email, photoURL,displayName} = result.user;const newUser = {isSignedIn: true,name: displayName,email: email,photo: photoURL,}setUser(newUser);console.log(user);})};

This code means that, if you can log in successfully you will find all of your information from the result. user. Then set a new user and pass the values of the properties and set it in the setUser. Hence, after successful authentication, you will see your name and photo in the UI like below.

🌟 Wow! You have successfully completed your first basic firebase project. I am giving the full codes of the App.js file so that you can easily implement it on your machine.

Full Code:

import ‘./App.css’;// Importing firebase servicesimport { initializeApp } from ‘firebase/app’;import { getAuth, signInWithPopup, GoogleAuthProvider,signOut } from “firebase/auth”;import { firebaseConfig } from ‘./firebase.config’;import { useState } from ‘react/cjs/react.development’;const provider = new GoogleAuthProvider();const app = initializeApp(firebaseConfig);const auth = getAuth();function App() {// Passing object in stateconst [user, setUser] = useState({isSignedIn: false,name: ‘’,email: ‘’,photo: ‘’,});const handleSignIn = () => {signInWithPopup(auth, provider).then((result) => {const {email, photoURL,displayName} = result.user;const newUser = {isSignedIn: true,name: displayName,email: email,photo: photoURL,}setUser(newUser);console.log(user);})};const handleSignOut =() =>{signOut(auth).then(() => {const signOutUser = {isSignedIn: false,name: ‘’,email: ‘’,photo: ‘’,};setUser(signOutUser);}).catch((error) => {// An error happened.});}return (<div className=”App”><img src={user.photo} alt={user.name} /><br />{/* Ternary operator */}{user.name ?<div><h2 style={{fontWeight: ‘bold’}}>Welcome, {user.name}</h2><button onClick={handleSignOut}>Sign In</button></div>:<div><h2>No user signed yet !!!</h2><button onClick={handleSignIn}>Sign In</button></div>}</div>);}export default App;

🌟 Wow! Quite interesting, right? Yeah, if you follow all the steps carefully. I am sure that you have created your first firebase project in a React App. If you can do this and understand every code, you will be able to apply other Authentication processes supplied by the firebase like “ Phone, Github, Email/Password, etc”.

Thank you for reading this article. Keep me in your’s prayer. And if you face any problems, feel free to ask me frankly via my Gmail (asif.eee.cu@gmail.com). If needed I will set a Google Meet session with you also.😊

Asif Ur Rahman
Technical Course Writer

--

--

Asif Ur Rahman
Asif Ur Rahman

Written by Asif Ur Rahman

Hi ! I am Asif. A full time web developer. || Web Developer at OmniGo || MERN Stack Developer

No responses yet