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.
Follow....

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) => {
            setUser(user)
        })
    }, [])

    const logInUser = () => {
        const provider = new GoogleAuthProvider()
        signInWithPopup(auth, provider)
            .then((res) => {
                setUser(res.user)
            })
            .catch((err) => {
                console.log(err)
            })
    }
    const logOutUser = () => {
        signOut(auth)
        setUser(null)
    }

    const value = {
        user,
        logInUser,
        logOutUser
    }
    return (
        <AuthCont.Provider value={user}>
            {children}
        </AuthCont.Provider>
    )
}
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"

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <AuthProvider>
      <App />
    </AuthProvider>
  </React.StrictMode>
)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)