In this simple project, we apply Firebase authentication using Google provider.
Preview Site:
After Sign in with Google account:
Let's create a Firebase project. Then we will connect with out project.
Step 1: Go to the Firebase project.
Step 2: Give your project name.
Step 3: Go build > Authentication.
Step 4: Enable Google Sign-in provider.
For more information, you can check this Firebase authentication (https://firebase.google.com/docs/auth?authuser=0&hl=en).
Step 5: Go to the project Setting.
Select the web project.
Project Create and Setup:
Run this cmd Commands:
npm create vite@latest name-of-your-project -- --template react
cd <your new project directory>
npm install react-router-dom localforage match-sorter sort-by
npm install firebase
Now we will create a file name firebase.init.js
in our project. In the given screenshot, the code we will copy and paste into a firebase.init.js
file.
The firebase.init.js
file:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
// firebase config.
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export default app;
Then add the last line export default app in firebase.init.js
file.
Now follow the code and try to do it.
App.jsx
import Login from "./Login"
function App() {
return (
<>
<Login></Login>
</>
)
}
export default App
Login.jsx
import { GoogleAuthProvider, getAuth, signInWithPopup, signOut } from 'firebase/auth';
import { useState } from 'react';
import app from './firebase.init';
import './login.css';
const Login = () => {
const [user, setUser] = useState(null);
const auth = getAuth(app);
const googleProvider = new GoogleAuthProvider();
// Sign in to the google.
const GoogleSignIn = () => {
signInWithPopup(auth, googleProvider)
.then((result) => {
const loggedInUser = result.user;
console.log(loggedInUser);
setUser(loggedInUser);
})
.catch(error => {
console.log('error', error.message);
})
}
// Signout.
const SignOut = () => {
signOut(auth)
.then(result => {
console.log(result);
setUser(null);
})
.catch(error => {
console.log(error);
})
}
return (
<div>
<h1>Google Signin with Firebase</h1>
{/* user ? logout : sign in. */}
{
user ?
<button onClick={SignOut}>Sign Out</button> :
<>
<button onClick={GoogleSignIn}>Google Login</button>
</>
}
{user && <div className='profile'>
<h2>Profile</h2>
<h4>User Name: {user.displayName}</h4>
<p>Email: {user.email}</p>
<img src={user.photoURL} alt="" />
</div>
}
</div>
);
};
export default Login;
Top comments (0)