Firebase Authentication in ReactJS

Firebase Authentication in ReactJS

Step-by-step guide for Firebase Authentication in ReactJS

I don't want to make this blog theoretical. I aim to explain the process of building authentication using Firebase and ReactJS. The blog is short and easy to understand, making it accessible for anyone to follow.

Step 1: Go to https://console.firebase.google.com/u/0/

Step 2: Create your Firebase project by clicking on 'Add Project'.

Step 3: Enter your project name and continue.

Step 4: Disable Google Analytics for your Firebase project and Create project.

Step 5: Click on the Authentication Card.

Step 6: Click on the Get started button.

Step 7: Choose the authentication sign-in method. In my case, I chose the Email/Password method. You can choose whichever method you prefer.

Step 8: Enable the Email/Password and click on the Save button.

Step 9: After clicking on Save button, you will see this window.

Step 10: Now, click on Project Overview and then click on the Web (</>) icon to get started by adding Firebase to your app.

Step 11: Give any name to your app to register it, then click the Register app button.

Step 12: After the previous step, you will see the Add Firebase SDK window. Don't close this window because we'll use this code to initialize Firebase.

Step 13: Initialize your ReactJS project. Copy the script and paste it in your terminal to initialize your project.

npx create-react-app your-project-name

Your project has been created successfully. Now, clean up all the pre-built code and write whatever I've shown you.

Step 14: Create a file called firebase.js in your src folder. Paste all the code written in Step 12, along with a few more lines to initialize Firebase Authentication and get a reference to the service.

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth"; // New Line Added

// 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 = {
  apiKey: "AIzaSyBs1sKGsmjqgv01a641wmCN4wARbESnZi4",
  authDomain: "auth-for-blog-9091a.firebaseapp.com",
  projectId: "auth-for-blog-9091a",
  storageBucket: "auth-for-blog-9091a.appspot.com",
  messagingSenderId: "751228759151",
  appId: "1:751228759151:web:faf3b51283ef866e8b719a"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Firebase Authentication and get a reference to the service
export const auth = getAuth(app); // New Line Added

How do I know that? I want to import getAuth from firebase/auth and export const auth = getAuth(app);.
Don't worry, I will tell you. First go to the https://firebase.google.com/docs/web/setup#available-libraries.

Click on "Authentication for Web". You will find the code to "Add and initialize the Authentication SDK". This is the code that I added to my project.

Step 15: Create SignIn.js and SignUp.js inside the auth folder. Create auth folder inside the components folder.

Step 15: Create SignIn.js and SignUp.js inside the "auth" folder. Create the "auth" folder inside the "components" folder.

Step 16: Code for SignIn.js

import React, { useState } from 'react'
import { auth } from '../../firebase'
import { signInWithEmailAndPassword } from 'firebase/auth';

function SignIn() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const signIn = (e) => {
    e.preventDefault();
    signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      console.log(userCredential);
    }).catch((error) => {
      console.log(error);
    })
  }

  return (
    <div className='sign-in-container'>
      <form onSubmit={signIn}>
        <h1>Log in to your account</h1>
        <input
          type="email"
          placeholder='Enter your email'
          value={email}
          onChange={e => setEmail(e.target.value)} />
        <input
          type="password"
          placeholder='Enter your password'
          value={password}
          onChange={e => setPassword(e.target.value)} />
          <button type='submit'>Log In</button>
      </form>
    </div>
  )
}

export default SignIn

Step 17: Code for SignUp.js

import React, { useState } from 'react'
import { auth } from '../../firebase'
import { createUserWithEmailAndPassword } from 'firebase/auth';

function SignUp() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const signUp = (e) => {
    e.preventDefault();
    createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {
      console.log(userCredential);
    }).catch((error) => {
      console.log(error);
    })
  }

  return (
    <div className='sign-in-container'>
      <form onSubmit={signUp}>
        <h1>Create an account</h1>
        <input
          type="email"
          placeholder='Enter your email'
          value={email}
          onChange={e => setEmail(e.target.value)} />
        <input
          type="password"
          placeholder='Enter your password'
          value={password}
          onChange={e => setPassword(e.target.value)} />
          <button type='submit'>Sign Up</button>
      </form>
    </div>
  )
}

export default SignUp

Step 18: Code for AuthDetails.js

import React, { useState, useEffect } from 'react'
import { auth } from '../firebase'
import { onAuthStateChanged, signOut } from 'firebase/auth';


function AuthDetails() {
  const [authUser, setAuthUser] = useState(null);

  useEffect(() => {
    const listen = onAuthStateChanged(auth, (user) => {
      if(user) {
        setAuthUser(user);
      } else {
        setAuthUser(null);
      }
    });

    return () => {
      listen();
    }
  }, [])

  const userSignOut = () => {
    signOut(auth).then(() => {
      console.log('Sign out successful')
    }).catch(error => console.log(error))
  }

  return (
    <div>
      { authUser ? <><p>{`Signed In ${authUser.email}`}</p><button onClick={userSignOut}>Sign Out</button></> : <p>Signed Out</p>}
    </div>
  )
}

export default AuthDetails

Step 19: Start your project.

npm start

Our project preview.

Step 20: Go to the Authentication page in Firebase. The data looks empty because no users have signed in yet.

Step 21: After Signing Up a user.

Final Step: Users' data are stored in the Firebase Authentication page.

I hope you found this blog helpful in understanding how to build your own authentication page using Firebase with ReactJS.

Thank you for reading my blog post. If you found it helpful, please like and share it with your colleagues.