DEV Community

Cover image for Firebase Google authentication with React
Md Amir Gauhar
Md Amir Gauhar

Posted on

Firebase Google authentication with React

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 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

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

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

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

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

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();
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

The whole code will look like this:
Alt Text

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;
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

Now let's import the Home component into our main App.js file. After importing it'll look something like the following:
Alt Text

Alt Text

Alt Text

Alt Text

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

Top comments (8)

Collapse
 
jacksonmmartins profile image
jacksonmmartins

Hello, I'm speaking from Brazil, thank you very much for your help, it was very important.

Collapse
 
mdamirgauhar profile image
Md Amir Gauhar

I’m glad. Thanks

Collapse
 
mahesh262 profile image
Mahesh262

it throws error like this
export 'firebase' (imported as 'firebase') was not found in './FireBase/firebase' (possible exports: initializeApp)

Collapse
 
mdamirgauhar profile image
Md Amir Gauhar

While using Firebase v.9, you need to import firebase from 'firebase/compat/app' and 'firebase/compat/auth' for auth

Collapse
 
ashishk1331 profile image
Ashish Khare😎

No!
Stencil/alpine + supabase = ❤

Collapse
 
mdamirgauhar profile image
Md Amir Gauhar

Haha man!! Whatever works for you...

Collapse
 
lylest profile image
wackyizzy • Edited

it failed
Attempted import error: 'firebase/app' does not contain a default

Collapse
 
surlejonathan profile image
surlejonathan

If you are using Firebase v.9, you need to import firebase from 'firebase/compat/app' and 'firebase/compat/auth' for auth