Google SignIn using Firebase Authentication in ReactJS
Last Updated :
23 May, 2024
Firebase simplifies mobile and web app development by offering pre-built features like user authentication (email/password, Google Sign-In, etc.) without the need to build complex backends. This saves time and resources for developers.
In this article, we will discuss about the Google Sign-In feature provided by Firebase.
Preview Image of Final Output:
Google SignIn using Firebase Authentication in ReactJSPrerequisites:
Approach to Implement Google SignIn using Firebase Authentication in ReactJS
- To integrate Google Sign-In authentication in a React application using Firebase, start by setting up your environment with
firebase
and creating a Firebase project to obtain your configuration details. - Initialize Firebase in your project with these configuration details.
- In your React component, use the Firebase Authentication module to set up Google Sign-In. Create functions to handle login and logout, using
signInWithPopup
for logging in and signOut
for logging out. - Manage the authentication state with React's
useState
and useEffect
hooks to update the UI based on the user's authentication status. - This setup allows users to sign in with their Google account, displaying their profile information and providing a logout option.
Steps to Create a ReactJS App and Installing Module:
Step 1: Setup to create the project
npm create vite@latest project_name -- --template react
To install the dependencies required by vite:
npm i
Also install firebase:
npm i firebase
This will install all dependencies required to run the project.
Updated Dependencies:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"firebase": "^10.8.1",
},
"devDependencies": {
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.34.1",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"vite": "^5.2.0"
}
Step 2: Update the project Structure. Inisde src folder create firebaseConfig.js file. Also delete all other files other than main.jsx. and index.css. Then Create App.jsx and App.css files
project_ structureStep 3: Connecting Firebase with the Application
- Navigate to the firebase website
- Go to the Console.
- Add Project.
Add new project- Now add project and give it desired name you want.
- After creating the project successfully, next page will appear choose the option of web, as shown.
Choose the web app- Now you have to enter the web app name, after that you will get your firebase configuration.
Copy the configuration- Now copy this configurtion, and paste it inside your firebaseConfig file inside src folder. If haven't, create it now. Also at the botton add to export the app. Like this:
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "AIzaSyArww-vMkxxfadfT7P-hYpY9Yx7mIje1CWROWI",
authDomain: "authexamplde-7f4d5dfa.firebaseapp.com",
projectId: "authexample-7f4dfdafd5",
storageBucket: "authexample-7fdfad4d5.appspot.com",
messagingSenderId: "4775906dfdf34303013",
appId: "1:477590603013:web:faaeda4ea3e2de6945a6e36c"
};
const app = initializeApp(firebaseConfig);
export {app};
- After that, save the configuration in firebase console, then choose the option of authentication.
Choose the Authentication- Go into the get started button, then choose Google provider under Sign-In method.
Choose Google as sign in providers- Now choose your support email and save it.
- After that firebase is connected to your web app, as well ready for authentication purpose.
Step 4: Implementing Sign-In Feature. We will use App component for our sigin implementation, as from here the app start.
In App.jsx we will use some particular function provided by firebase library:
Functions from firebase/auth:
- getAuth: Retrieves the Firebase authentication instance from the provided app configuration.
- GoogleAuthProvider: Creates a Google authentication provider object.
- signInWithPopup: Initiates a sign-in flow using a popup window or redirect.
Example: Below is an Example to Google SignIn using Firebase Authentication in ReactJS
CSS
.container{
height: 100vh;
width: 100vw;
align-content: center;
display: flex;
.btn{
width: 15rem;
margin: auto;
cursor: pointer;
}
.user{
padding: 5rem;
border: 2px solid white;
border-radius: 5px;
box-shadow: 0 0 1rem white;
width: 50%;
margin: auto;
align-content: center;
img{
box-shadow: 0 0 .5rem rgb(0, 255, 255);
}
}
.logout{
box-shadow: 0 0 .3rem rgb(184, 104, 104);
margin-left: 10rem;
background-color: rgb(212, 22, 22);
}
}
JavaScript
import { useEffect, useState } from "react";
import { app } from "./firebaseConfig";
import {getAuth, GoogleAuthProvider, signInWithPopup} from "firebase/auth";
const auth = getAuth(app)
const provider = new GoogleAuthProvider();
import "./App.css";
const App = () => {
const [user, setUser] = useState(null);
const handleLogin = () => {
signInWithPopup(auth, provider)
.then((result) => {
setUser(result.user);
console.log(result.user)
})
.catch((error) => console.log(error));
};
const handleLogout = () => {
setUser(null);
auth.signOut();
}
useEffect(()=>{
console.log(user)
},[user])
return (
<div className="container">
{!user && (
<img
className="btn"
onClick={() => handleLogin()}
src="https://media.geeksforgeeks.org/wp-content/uploads/20240520175106/Google_SignIn_Logo.png"
alt="NA"
/>
)}
{user && (
<>
<div className="user">
<h1>Your Successfully Loged In</h1>
<h2>Name: {user.displayName}</h2>
<h2>Email: {user.email}</h2>
<img src={user.photoURL} alt="N/A" />
<button onClick={() => handleLogout()} className="logout">Log Out</button>
</div>
</>
)}
</div>
);
};
export default App;
JavaScript
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "AIzaSyArww-vMkxxfadfT7P-hYpY9Yx7mIje1CWROWI",
authDomain: "authexamplde-7f4d5dfa.firebaseapp.com",
projectId: "authexample-7f4dfdafd5",
storageBucket: "authexample-7fdfad4d5.appspot.com",
messagingSenderId: "4775906dfdf34303013",
appId: "1:477590603013:web:faaeda4ea3e2de6945a6e36c"
};
const app = initializeApp(firebaseConfig);
export {app};
Flow of control in App.jsx
- When the user clicks the Google Sign In button, handleLogin is called.
- Firebase initiates a sign-in flow using a popup window.
- Upon successful login, the user's information is stored in the user state, and their details are displayed.
- The "Log Out" button calls handleLogout to sign the user out and reset the state.
Start using the below command:
npm run dev
Output:
Also, you can see that inside Firebase data of users is being stored:
Users List inside firebase
Similar Reads
Google Signing using Firebase Authentication in Kotlin
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. Google Sign-In is a secure way to
5 min read
Google Signing using Firebase Authentication in Android
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building the backend for user authentication. Google Sign-In is a secure way to
8 min read
How to authenticate with google using firebase in React ?
The following approach covers how to authenticate with Google using firebase in react. We have used firebase module to achieve so.Creating React Application And Installing Module:Step 1: Create a React myapp using the following command:npx create-react-app myappStep 2: After creating your project fo
2 min read
Google Authentication with Firebase
Google Authentication, a method of verifying user identities using Google credentials, provides a seamless and secure way for users to sign in to applications. With the help of Firebase, developers can integrate Google Authentication into their apps and allowing users to sign in with their existing
5 min read
Anonymous authentication in firebase using React JS
This method explains how to sign in without revealing your identity using Firebase in a React app. It's like having a secret entry you create and use temporary anonymous accounts for logging in. We make it happen by using the special tools provided by Firebase.Prerequisites:React JSFirebaseApproach
3 min read
How to authenticate phone number using firebase in ReactJS ?
User authentication is a critical aspect of many web applications, and phone number authentication has become increasingly popular for its convenience and security. Firebase, a powerful platform developed by Google, offers various authentication methods, including phone number authentication. Prereq
3 min read
How to authenticate firebase with GitHub in ReactJS ?
The following approach covers how to authenticate firebase with GitHub in react. We have used the firebase module to achieve so.Creating React Application And Installing Module:Step 1: Create a React app using the following command:npx create-react-app gfgappStep 2: After creating your project folde
2 min read
Google Authentication using Passport in Node.js
The following approach covers how to authenticate with google using passport in nodeJs. Authentication is basically the verification of users before granting them access to the website or services. Authentication which is done using a Google account is called Google Authentication. We can do Google
2 min read
How to get current date and time in firebase using ReactJS ?
This article provides a detailed walkthrough on obtaining the current date and time in a Firebase environment using ReactJS. Readers will gain insights into the implementation process, enabling date and time functionalities into their React projects powered by Firebase.Prerequisites:Node JS or NPMRe
2 min read
How to Use Authentication Console in Firebase?
Almost all apps need to have some permission system in place. In some circumstances, checking a username/password pair against our Users table is sufficient. Still, frequently, we require a more detailed permissions model to grant specific users access to particular resources while preventing them f
4 min read