DEV Community

Cover image for React Firebase Authentication tutorial
Muhammad Shahryiar
Muhammad Shahryiar

Posted on

React Firebase Authentication tutorial

Learn how to use Firebase authentication for user registration, sign-in functionality for end users. It provides an end-to-end identity solution, supporting email and password accounts, phone authentication and social media logins. In this tutorial, we will look at Firebase authentication using Email and Password.

1. Create Firebase Project

First, visit Firebase Console using the following URL – https://console.firebase.google.com. Login using your Google Account – You will be able to create a new project in only 3 Steps.

I. Create a new project. Give it a name and click continue.

Image description

II. Next you will be asked if you want Google Analytics for your project. You can skip this step and come back to it later.

Image description

III. After that, it will start to create your new project on Firebase. The process should take just a few seconds, once done click continue and you will be taken to projects homepage.

Image description

Image description

Image description

2. Install Firebase CLI

Install Firebase using npm:

npm install firebase

3. Initialize Firebase

Initialize Firebase in your app and create a Firebase App object. Furthermore, You will find your firebase config in your project settings, after you add your App in the project.

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore/lite';
import { getAuth  } from "firebase/auth";

const firebaseConfig = {
    apiKey: "**************",
    authDomain: "*********.firebaseapp.com",
    projectId: "*********",
    storageBucket: "*********.appspot.com",
    messagingSenderId: "*********",
    appId: "***********"
  };


const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore(app);

export {auth , db};
Enter fullscreen mode Exit fullscreen mode

Put the above lines of code in firebaseHandler.js ( or any other name you want for your Firebase Configuration file ).

Image description
Connect Firebase to your app to start using it

Image description

Image description
Firebase Configuration

Once you add your web app to Firebase, you will have access to Firebase Config file, which will let you connect to Firebase and use required resources. Firebase configuration will be under Project Settings.

Finally, the connectivity between our app and Firebase is done. We can now move on to Authentication using Firebase and React.

4. Redux Introduction

To begin with, Redux is state management for your react app. It stores information in a store (centralized location). It manages the state and data of your application.

Building Parts of redux:

  • Action:
    Actions are payload of information that send data from your application to your store. They are the only source of information for the store. This means if any state change is necessary the change required will be dispatched through the actions.

  • Reducer:
    “Actions describe the fact that something happened, but don’t specify how the application’s state changes in response. This is the job of reducers.”

When an action is dispatched for state change, it’s the reducers duty to make the necessary change to the state and return the new state of the application.

  • Store: A Store can be created with the help of reducers which holds the entire state of the application. The recommended way is to use a single store for the entire application rather than having multiple stores which will violate the use of redux, which only has a single store.

Image description

  • Install Redux
# NPM
npm install @reduxjs/toolkit
Enter fullscreen mode Exit fullscreen mode
  • Create a Redux React App
# Redux + Plain JS template
npx create-react-app my-app --template redux
Enter fullscreen mode Exit fullscreen mode
  • Creating Slice for storing User Information
import {  createSlice } from '@reduxjs/toolkit';

const initialState = {
  user: null,
};

export const userSlice = createSlice({
  name: 'user',
  initialState,

  reducers: {
    login:(state, action)=>{
      state.user = action.payload;
    },
    logout:(state, action)=>{
      state.user = null;
    }
  }
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;


export default userSlice.reducer;
Enter fullscreen mode Exit fullscreen mode
  • Configured Store that holds the entire state of the user/application
import { configureStore } from '@reduxjs/toolkit';
import userReducer from '../features/userSlice';

export const store = configureStore({
  reducer: {
    user: userReducer,
  },
});
Enter fullscreen mode Exit fullscreen mode

The above code, creates a user slice to store user information (centrally), with some initial state value.

Reducers are pure functions in Redux, which are the only way to change states in Redux. It is the only place where you can write logic and calculations. Reducer function will accept the previous state of app and action being dispatched, calculate the next state and returns the new object.

So, in the above code, we have used two reducers. Login and Logout. Once the user enters correct information, the login reducer will be activated, and it will update the user state to the logged in user’s state.

While, logout reducer will set the user state to null, which will update across the entire app, thanks to the redux.

5. Sign In and user registration using Firebase Authentication

import React, { useRef } from 'react'
import "./signUpScreen.css";


// importing from our Firebase Config file.
import { auth } from '../firebaseHandler';


// Importing functions from Firebase Authentication
import {createUserWithEmailAndPassword,signInWithEmailAndPassword  } from "firebase/auth";


// Creates a new User 
function SignUpScreen() {
  const emailRef = useRef(null);
  const passwordRef = useRef(null);

  const register = (e) => { 
    e.preventDefault();   

    createUserWithEmailAndPassword(auth, emailRef.current.value, passwordRef.current.value)           
          .then((authUser)=>{
            console.log(authUser)
        }).catch(error=>{
          alert(error.message)
        });

  }



// Sign In using Email and Password
  const signIn = (e) => { 
    e.preventDefault();

    signInWithEmailAndPassword(auth, emailRef.current.value, passwordRef.current.value)
    .then((authUser)=>{
      console.log(authUser);
    }).catch(error=>{
      alert(error.message)
    });

}

  return (
    <div className='signUpScreen'>
      <form>
        <h1>Sign In</h1>
        <input ref={emailRef} placeholder='Email' type="input"/>
        <input ref={passwordRef} placeholder='Password' type="password"/>
        <button type='submit' onClick={signIn}>Sign In</button>

        <h4>New to Netflix? <strong onClick={register}>Sign up now.</strong></h4>
      </form>
    </div>
  )
}

export default SignUpScreen;
Enter fullscreen mode Exit fullscreen mode

In addition, we are going to use Firebase’s built-in:

CreateUserWithEmailAndPassword,
signInWithEmailAndPassword

functions to register users using Firebase. And once the registration is successful, helps to easily login.

6. React Navigation and Authentication

If you have ever coded in React before, you will definitely know App.js file in react projects. It’s the essential file in every React App.

We will now implement React Navigation to navigate to different pages, based on whether user is logged in or not.

import React, { useEffect } from 'react';
import './App.css';

import HomeScreen from './screens/HomeScreen';
import ProfileScreen from './screens/ProfileScreen';

import {BrowserRouter, Routes, Route} from "react-router-dom";
import LoginScreen from './screens/LoginScreen';
import { auth } from './firebaseHandler';
import { useDispatch, useSelector } from "react-redux";
import { login,logout, selectUser } from './features/userSlice';

function App() {
  const user = useSelector(selectUser);
  const dispatch = useDispatch();

  useEffect(()=>{
    const unsubscribe = auth.onAuthStateChanged(userAuth=>{
      if(userAuth){
        //Logged In
        dispatch(
          login({
          uid:userAuth.uid,
          email:userAuth.email,
        })
        );
      }
      else{
        // Logged Out
        dispatch(logout());
      }
    })

    return unsubscribe;

  },[dispatch]);


  return (
    <div className="app">
      <BrowserRouter>
      {
        !user  ? (
          <LoginScreen/>
        ) : (

        <Routes>
          <Route path="/" element={<HomeScreen/>}/>
          <Route path="/profile" element={<ProfileScreen/>}/>
        </Routes>
        )

      }
      </BrowserRouter>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

App.js

  • useSelector
    useSelector, selects logged in user from redux user’s Slice.

  • useDispatch
    useDispatch dispatches user’s information to redux user’s slice.

  • Login
    We created Login Reducer earlier, which helps us to stores user information.

  • Logout
    Finally, logout will clear the user’s state.

Thank you for reading till the end. We now know how to implement Firebase Authentication in react. It took me sometime to figure out how to implement Firebase version 9.8.4, because a lot has changed from version 8 to version 9. I hope this blog article helps others to properly implement Firebase Authentication.

Moreover, we have also implemented React Navigation in our project as well. Which helps us to navigate to a different page. The complete article on React Navigation is available here.

The Github link to the whole repository is here. For more articles, you can visit my blog: TechwithSherry.

Top comments (0)