DEV Community

Kunal Agrawal
Kunal Agrawal

Posted on


Authentication Using Firebase in React App. 🤺🔥

In this article we will know how to authenticate users, in your web app. For this article I'm using google authentication.

Create a Firebase Project

It's simple, just login with your google account in firebase, create a new project.
Image description

In that project go to Authentication's tab.
Image description

Click on Sign-in method
Image description
Go to Add New Provider, select Google.
Image description

Now, you need to create a web app in your project
Image description
Image description
Image description
Copy the configuration file.
Now, open your fav IDE and create a React Project.
In src folder create a file name fb.config.js / .ts
Image description
also, don't forget to install firebase.

npm i firebase
Enter fullscreen mode Exit fullscreen mode

we're using context to use state of user authentication in our app. create a authContext.tsx file.

import { createContext, ReactComponentElement, ReactElement, useContext, useEffect, useState } from 'react'
import { User, GoogleAuthProvider, signInWithPopup, signOut, onAuthStateChanged } from "firebase/auth"
import { auth, app } from "./fb.config"

interface value {
    user: User | null,
    logInUser: () => void,
    logOutUser: () => void,

const AuthCont = createContext<User | null>(null)

export const useAuthContext = () => {
    return useContext(AuthCont)

export default function authContext({ children }: { children: ReactElement }) {
    const [user, setUser] = useState<null | User>(null)
    useEffect(() => {
        onAuthStateChanged(auth, (user) => {
    }, [])

    const logInUser = () => {
        const provider = new GoogleAuthProvider()
        signInWithPopup(auth, provider)
            .then((res) => {
            .catch((err) => {
    const logOutUser = () => {

    const value = {
    return (
        <AuthCont.Provider value={user}>
Enter fullscreen mode Exit fullscreen mode

Now we just need to put this on top of our app.tsx, then we can use it in any child component.
Go to main.tsx file and put this code.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import AuthProvider from "./authContext"

      <App />
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

👀 Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.