DEV Community

Cover image for HOW TO SETUP FIREBASE AUTHENTICATION ON A REACT PROJECT
Dev. Zubby Okere
Dev. Zubby Okere

Posted on • Updated on

HOW TO SETUP FIREBASE AUTHENTICATION ON A REACT PROJECT

INTRODUCTION

Setting up a method of authentication for users is a really good way of improving the outlook of your web application. You might have some protected routes that you only want authenticated and signed in users to have access to. There are many ways to set up authentication, including using a backend, using Nextjs authentication or firebase authentication, among so many others. This article is going to cover authentication with firebase. Firebase is a technology that provides a lot of backend services. It is generally referred to as backend as a service(BaaS). It’s owned by google and provides a wide range of services including; real-time database, cloud storage, hosting and authentication, which is what we’d cover in this article. Before you continue, this tutorial is for those who are already comfortable using React and not for absolute beginners.

Authentication With Firebase

Authenticating users using firebase is very simple, using the firebase SDK, you can set up authentication with phone numbers, email and password, which is the most popular. You can also set up authentication with other third party services like Google, Twitter, Apple, Microsoft, Facebook, GitHub, etc. Authentication with firebase can be used for web applications, iOS applications, android applications, etc. and with a lot of programming languages and frameworks. This article is going to cover authentication for web applications and more specifically, authentication with email and password, in React. Auth and authentication will be used interchangeably throughout the course of this article, they both mean the same thing.

Getting Started With Email/Password Authentication

Before you integrate firebase authentication in your React project, you’d have to have a google account which you’d then use to create a firebase account. After doing all the necessary authentication, you click here to get started with a new project. When you get in, click on the “get started” button you see. It will lead you to a page where you can add a project. Click on the “add project” button to add one. Give the project a name. It could be anything. You could use “my-auth-project,” if you like. And then, continue. You’d be asked to enable google analytics for the project, you can decline that and click on “create project.” Wait some seconds for it to create your new project. Now that your new project has been created, click on “continue.” You’d get to an interface where you’d see many options, you can choose whatever you want to implement. For auth, click on authentication and that will lead you to a new interface where you can choose how you want to authenticate users. Click on email/password. After that, make sure you enable email/password and click on save. You’d see a new interface, an empty one without any authenticated user.
Now navigate to VSCODE and create a new React project using “npx create-react-app auth”, “auth” is the name of the react project here. You can give it any name or just give a space and add “.”, After CRA. After that, make sure you’re in the auth directory and install firebase into your application using; “npm i firebase”, this will install firebase for you. Now go back to firebase, to the project you created initially and click on the web project icon “</>” you see there. The third one from the left. Just like you can see in the image below;

Image description

Now give it a nickname as they’ve requested. It could be any name. After you’ve done that, click on “register” app. This will lead you to another interface where you’d be required to install firebase using Npm. We already did that. Now, skip that and move to the next, which is copying the code firebase has provided. Create a firebase.js file on the src directory, this is where you’d paste the code to initialize firebase in your React application. This is where all of your firebase configurations for your React project will happen. Again, the pasted code is used to initialize firebase in your application. Take a look at the code snippet below;

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
// 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: "AIzaSyARMzfqJbdwtsPVQCiR0qEM96P_fj1acuE",
  authDomain: "my-auth-project-744de.firebaseapp.com",
  projectId: "my-auth-project-744de",
  storageBucket: "my-auth-project-744de.appspot.com",
  messagingSenderId: "908733099316",
  appId: "1:908733099316:web:089d2658ec0910dc148961"
};

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

Enter fullscreen mode Exit fullscreen mode

Remember to use your own, they are all unique, both project and app IDs and keys.

Now that you’ve done that, you have to tell firebase that you are using authentication on your project and how you’d do that is by initializing firebase auth in your firebase.js configuration. Check the updated code below;

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
// 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: "AIzaSyARMzfqJbdwtsPVQCiR0qEM96P_fj1acuE",
  authDomain: "my-auth-project-744de.firebaseapp.com",
  projectId: "my-auth-project-744de",
  storageBucket: "my-auth-project-744de.appspot.com",
  messagingSenderId: "908733099316",
  appId: "1:908733099316:web:089d2658ec0910dc148961"
};

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

// Initialize Firebase Authentication and get a reference to the service
export const auth = getAuth(app);
export default app;

Enter fullscreen mode Exit fullscreen mode

By initializing firebase auth in the code above, you’ve now added a reference to the firebase authentication service.

Implementing authentication in your project

Now that you have done the necessary configurations, you have to start implementing authentication in your project. You can do this however you like, but this is going to be a very simple one with no styling at all, it will be mainly focused on the logic of implementing authentication in your project. Now, create a components folder and in that folder, create another one. You can call it “auth”. In this “auth” folder, create two files. I’d call these files “signUp” and “signIn”, you can do the same.

In the signUp file, create a functional arrow component using the VSCODE shortcut, RAFCE, create a form and implement the logic. Take a look at the code snippet below on how to implement the signup functionality;

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

const Signup = () => {
   const [email, setEmail] = useState('')
    const [password, setPassword] = useState('');

    const userSignUp = (e) => {
      e.preventDefault()
createUserWithEmailAndPassword(auth, email, password).then((userCredential) => {
            // Signed in
            const user = userCredential.user;
            console.log(user);

        }) .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(errorCode, errorMessage);

        });


    }

  return (
<section>
   <div>
      <div>                  
        <h1> Create Account <h1>                                                                            

<form onSubmit=“userSignUp”>                                                                                          
 <div>
  <input type="email"
  value={email}
  onChange={(e) =>      setEmail(e.target.value)}  
 required                                    
  placeholder="Enter your email address…"/>
 </div>

<div>
 <input type="password"
 value={password}
 onChange={(e) => setPassword(e.target.value)} 
required                                 
placeholder="Enter your password…" />
 </div>                                             
 <button type="submit" 
onClick={userSignUp}>  
    Sign up                                
 </button>
                                                                     </form>
</div>
 </div>
 </section>
  )
}

export default Signup

Enter fullscreen mode Exit fullscreen mode

Using the code snippet above, you’d be able to easily create a signup functionality in your application using firebase.

In the signIn file, use RAFCE, which is a VSCODE shortcut for creating a functional arrow component. And create a form and implement the logic for signing in users, you can use the code snippet below;




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

const Login = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const userLogin = (e) => {
        e.preventDefault();
        signInWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            // Signed in
            const user = userCredential.user;
             console.log(user);
        }) .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(errorCode, errorMessage)
        });

    }

    return(
        <>

                <section>
                    <div>                                            
                        <p>Login into your account</p>                       

                        <form>                                              
                            <div>

                                <input 
                                    Value=“email”
                                    type="email"                                    
                                    required                                                                                
                                    placeholder="Enter your email address…"
                                    onChange={(e)=>setEmail(e.target.value)}
                                />
                            </div>

                            <div>
                             <input 
                                value=“password”
                                type="email"
                                required
                                placeholder="Enter your password…"
                                onChange={(e)=>setPassword(e.target.value)}/>
                            </div>

                            <div>
                                <button onClick={userLogin}>      
                                    Login                                                                  
                                </button>
                            </div>                               
                        </form>


                    </div>
                </section>

        </>
    )
}

export default Login

Enter fullscreen mode Exit fullscreen mode

The code above handles authentication for users that have already signed up and just have to sign in.

For the signup functionality, once a user signs up, it reflects on your firebase console. You get to see the details of the user that just signed up. You’d see the time stamp, the provider, and also the unique user id.

The next functionality is an authentication state observer which is going to check which user is signed in and how a user that’s signed in can sign out. This can be created in another file which you can name authDetails.js or anything you like. Check the code snippet below:


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

const AuthDetails = () => {
Const [authUser, setAuthUser]=useState(null)

    useEffect(()=>{
        onAuthStateChanged(auth, (user) => {
            if (user) {
              setAuthUser(user)
              // User is signed in, see docs for a list of available properties
              // https://firebase.google.com/docs/reference/js/firebase.User
              const uid = user.uid;
              // ...
              console.log("uid", uid)
            } else {
              setAuthUser(null)
              // User is signed out
              // ...
              console.log("user is logged out")
            }
          });
        return ()=>{
            listen()
          }
    }, [])
 //this logic is for logging out a signed in user
const handleLogout = () => {               
        signOut(auth).then(() => {
        // Sign-out successful.
           console.log("Signed out successfully")
        }).catch((error) => {
        // An error happened.
        });
    }
  return (
    <div>        
//this shows if a user is signed in and the user email.
     {authUser ? <p>{`user is signed in as ${authUser.email}`}</p>
//this button is for logging out a signed in user
<button onClick={handleLogout}>Sign Out</button>
: <p>User signed Out</p>
//if the second condition is met, that means user is signed out, the text “User signed Out” will show.
    </div>
  )
}

export default AuthDetails

Enter fullscreen mode Exit fullscreen mode

In conclusion, firebase authentication is easy to implement and helps you register, sign in and sign out new users, seamlessly. I hope this was helpful. If you found this helpful, kindly follow me on Twitter or on LinkedIn and let’s connect.

Top comments (2)

Collapse
 
byokpara profile image
𝐕𝐈

Another great article! Keep up the good work!

Collapse
 
zubby_dev profile image
Dev. Zubby Okere

Thanks for reading!