Firebase Google authentication with React
Tags: firebase, react, google, authentication
Published: 2021-08-13 18:49:14

Hellooo, my fellow developers.
Today we're going to learn about authenticating our react app with google sign-in using Firebase.

First of all let us talk a little bit about what actually Firebase is.
**Google Firebase** is a Google-backed application development software that enables developers to develop iOS, Android and Web apps. Firebase provides tools for tracking analytics, reporting and fixing app crashes, creating marketing and product experiment.Firebase offers a number of services, including:
1. Analytics 
2. Authentication 
3. Cloud messaging 
4. Realtime database
5. Performance and many more...

Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

Now let's jump into our project.

First of all we’ll setup our Firebase project. To do that go to [firebase.google.com](firebase.google.com) and login in with our google account. We’ll now initialize our app.

Click on **Get Started** or **Go to console** at the top right of the webpage.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x32amjykyo9klcjzok71.png)

Now we’ll be taken to **Add Project** page. Select Add project and keep the project name whatever you like. Now it’ll ask us to choose a Firebase account. We’ll choose the default one. After that it'll redirect us to the Project Overview page.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8wfx2sseh1mm06aax7t7.png)

To add an app click on the web icon. It’ll allow us to create an app and allow us to give a nickname to our app. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tshednpr4iuno32gvnf4.png)

Now after registering our app let’s copy the firebaseConfig object which will help us later to initialize our web app and connect it with firebase. The config object will look something like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5rwluiqh24j0hq4na2oq.png)

Now to enable the authentication, let’s get back to project overview page and click on the authentication tab then set up sign-in method and  enable the Google authentication.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73ea0tl1qsm31a8hskq8.png)

**Yaay!!!**  we are done with the first part of our project. Now here comes the fun part. Let’s write some code.

To begin with coding first of all we’ll create our starter project directory using the following command in the terminal:
> npx create-react-app google-auth    _//google-auth is my directory name_

It will create a basic react app boilerplate for us.

Now we’ll install firebase in our app using the following command in the terminal:
> npm install firebase

**Note** If you’re installing firebase for the first time on your system, type the following in the terminal:
> npm install -g firebase-tools

Now let's put all that to our use.
We’ll create a service folder and add firebase.js into it and add the following code.

_src/service/firebase.js_

```
import firebase from "firebase/app";
import 'firebase/auth';

const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "PROJECT_ID.firebaseapp.com",
  databaseURL: "https://PROJECT_ID.firebaseio.com",
  projectId: "PROJECT_ID",
  storageBucket: "PROJECT_ID.appspot.com",
  messagingSenderId: "SENDER_ID",
  appId: "APP_ID",
  measurementId: "G-MEASUREMENT_ID",
};

// Initialize Firebase 
firebase.initializeApp(firebaseConfig);

export const auth = firebase.auth();
```
Next we’ll create a sign-in function which will let us sign-in with google.

_src/service/firebase.js_ 
```
export const auth = firebase.auth();

const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });

export const signInWithGoogle = () => auth.signInWithPopup(provider);
```
The whole code will look like this:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ilmx5a107qgbgt0iwiyp.png)

To use this function, we’ll import it to our Login component and add a onClick handler on the sign in button. So. lets create a Login component inside a components folder and add the following code:

_src/compenents/Login.js_
```
import { signInWithGoogle } from '../services/firebase';

import '../App.css';

const Login = () => {
  return (
    <div>
      <button className="button" onClick={signInWithGoogle}><i className="fab fa-google"></i>Sign in with google</button>
    </div>
  )
}

export default Login;
```
Let's import the Login component into our App.js file.
And that’s it. We can now sign-in to our app via our google accounts.

Now let us store the user information so that we can use it in our application. In the App.js file add the following codes.

_src/App.js_
```
import { useState, useEffect } from 'react';

import Login from './components/Login';
import Home from './components/Home';
import firebase from './services/firebase';

import './App.css';



function App() {
  const [user, setUser] = useState(null);

  useEffect(() => {
    firebase.auth().onAuthStateChanged(user => {
      setUser(user);
    })
  }, [])

  console.log(user);

  return (
    <div className="app">
      <Login />
    </div>
  );
}

export default App;

```
Let's create a Home component to use the information that we got after logging in. Create a Home Component inside the components app and add the following code into it:

_src/components/Home.js_
```
import React from 'react';

import { auth } from '../services/firebase'

import '../App.css';

const Home = ({ user }) => {
  return (
    <div className="home">
      <h1>Hello, <span></span>{user.displayName}</h1>
      <img src={user.photoURL} alt="" />
      <button className="button signout" onClick={() => auth.signOut()}>Sign out</button>
    </div>
  )
}

export default Home;

```
Now let's import the Home component into our main App.js file. After importing it'll look something like the following:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pu88togkdzu2syba3c4a.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kylro3mkiq6sozl14z3w.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6eqnvn0n9rkoujbt97c.jpg)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/766zwurxj1e835nbaabl.png)


**_Voila_**, we just created a mini app where we can login with our google account.
Hope you all liked it....