Simplest and the Fastest Way to Authenticate your React App

Simplest and the Fastest Way to Authenticate your React App

That I have found

By the end of this blog, you will know how to

  1. Login a User
  2. Logout a user
  3. And show the content to logged-in users only

I will share with you the fastest and the most straightforward way I have found and used to make authentication for my web app

Step 1: Make a firebase project

Link: https://console.firebase.google.com/u/0/

If you don't already have an account make one! firebase is awesome it makes working on front-end very easy since it takes care of Hosting, Auth, and Storage for us.

Click on Add Project and go through the steps and make a project

Make a firebase.js file and add all the given info

import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: "...Your Info...",
  authDomain: "...Your Info..."
  projectId: "...Your Info...",
  storageBucket: "...Your Info...",
  messagingSenderId: "...Your Info...",
  appId: "...Your Info...",
  measurementId: "...Your Info...",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

Step 2: Add firebase auth

Then Once inside the firebase console click on Firebase Authentication

Untitled.png

Step 3: Select an auth provider

Inside the Sign in method Select Google as your provider

You can use any other or multiple Providers!!

Untitled.png

Step 4: Add firebase and react-firebase hooks as a dependency in your project

yarn add firebase react-firebase-hooks

or

npm install firebase react-firebase-hooks

Step 5: Make your Login page

Here’s the code for a basic login page

import { LogIn } from "./firebase";

export default function Login() {
  return (
    <div className="login">
      <div className="login__logo">
        <img
          src="https://i.pinimg.com/originals/26/0e/26/260e26a01c33fe8c726ffa20fd6809e1.jpg"
          alt="logo"
        />
      </div>
      <button onClick={LogIn}>Log in</button>
    </div>
  );
}

Here is the CSS

.login {
  display: grid;
  place-items: center;
  height: 100vh;
  background-color: black;
}

.login > button {
  width: 300px;
  height: 50px;
  background-color: white;
  font-weight: 800;
  font-size: larger;
  border-radius: 2rem;
}

.login > button:hover {
  background-color: rgb(114, 114, 114);
  color: white;
}

.login > div > img {
  object-fit: contain;
  height: 150px;
}

The Result

image.png

Now the Coding starts!

Step 6:Make a firebase.js file inside the src folder

Import the following functions from firebase

import {
  getAuth,
  GoogleAuthProvider,
  signInWithPopup,
  signOut,
} from "firebase/auth";

also

//Auth
export const auth = getAuth();
const provider = new GoogleAuthProvider();

Step 7: in App.js

Import the following hook and our auth from firebase.js

import { useAuthState } from "react-firebase-hooks/auth";
import { auth } from "./firebase";

Now we are going to use this hook if the user if logged in with a simple Inline If-Else statement

function App() {
  const [user] = useAuthState(auth);

  return (
    <div className="App">
      {user ? (
          <Home user={user} />
      ) : (
        <Login />
      )}
    </div>
  );
}

export default App;

In firebase.js

Step 8: Make the Login function

We will use the signInWithPopup function from firebase and our auth and provider from the firebase file

export const logIn= () => {
    signInWithPopup(auth, provider).catch((error) => {
      alert(error.message);
    });
  };

And that's it we have created the login functionality for our web app

Step 9: Logout function

we will create a logout function just below our login function

export const logOut = () => {
  signOut(auth)
    .then(() => {
      console.log("User Logged Out");
    })
    .catch((err) => {
      alert(err.message);
    });
};

Now we will simply import it into the files we need

In Login.jsx

import { logIn } from "./firebase";

export default function Login() {
  return (
    <div className="login">
      <div className="login__logo">
        <img
          src="https://i.pinimg.com/originals/26/0e/26/260e26a01c33fe8c726ffa20fd6809e1.jpg"
          alt="logo"
        />
      </div>
      <button onClick={logIn}>Log in</button>
    </div>
  );
}

In Home.Jsx

import React from "react";
import { logOut } from "./firebase";

export const Home = () => {
  return (
    <>
      <div className="Home">Super Duper Secret App</div>
      <button onClick={logOut}>Logout</button>
    </>
  );
};

The Complete code