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.
In that project go to Authentication's tab.
Click on Sign-in method
Go to Add New Provider, select Google.
Now, you need to create a web app in your project
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
also, don't forget to install firebase.
npm i firebase
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>
)
}
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>
)
Top comments (0)