Firebase Authentication in React.js

Mahir Uslu
3 min readDec 17, 2022

--

React with Firebase Series #2

In this article, you’ll learn how to secure data and manage the app authentication after setting up and implementing firebase to the project.

This article is the sequel following article;

“I never dreamed about success. I worked for it.” — Estée Lauder

After setting up firebase and making sure that everything runs correctly, we have to manage authentication. Actually not have to, but we should. Why am I saying this? Because if we don’t wanna set up authentication we have another option, we can make our database public in the rules section.

This way our database is readable and writable without authentication but also by anyone who wants!

This is a security breach. Do not use this usage.

Let's dive into our main subject.

I’ll show you how to sign in and sign up. You’ll get the idea. Use it everywhere you need with revisions.

First, we need to import authentication functions from firebase. And initialize a variable named ‘auth’ from getAuth function. Sign in method take 3 parameters, in order of; auth variable, email and password. After all these our useFirebase hook should look like this;

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
import {
getAuth,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
} from "firebase/auth";

const firebaseConfig = {
apiKey: "*****",
authDomain: "*****",
databaseURL: "*****",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "*****",
appId: "*****",
};

const app = initializeApp(firebaseConfig);
export const db = getDatabase(app);

const auth = getAuth();

export const signIn = (email, password) => {
return signInWithEmailAndPassword(auth, email, password);
};

export const signUp = (email, password) => {
return createUserWithEmailAndPassword(auth, email, password);
};

The hook is ready. Let’s use it.

On our sign-in/up page call the method that we created before in hook, and in the handle submit function call this promise.

This promise will return a response if it is succeeded or throw an error.

If it is succeeded, set auth token to session storage for further usage.

You can find that token in the following expression, res._tokenResponse.refreshToken

After that navigate the user to a page.

An example of it;

const handleSubmit = (e) => {
e.preventDefault();
signIn(email, password)
.then((res) => {
sessionStorage.setItem("Auth Token", res._tokenResponse.refreshToken);

navigate("/admin");
})
.catch((err) => {
console.log(err.message);
});
};

That’s all folks. It is easier than it looks...

Hope you enjoyed it!

Other articles from this series;

--

--