DEV Community

Dylan Muraco
Dylan Muraco

Posted on

Authenticate in React with Firebase Auth

Authentication is something almost every modern web app needs. I've user Auth0 and Next Auth but Firebase seems to provide the easiest way to get authentication up and running.

Registering a Firebase App

Now we need to create a new project in firebase. Navigate to Firebase Console and click Add project
Image description

After creating this project and you are in the project console click on the Web icon to create a new web app. Follow the directions and copy the config which will look something like this.
Image description

After creating this project navigate to the authentication tab and click Get Started. Then click Google

Getting Started

npm install firebase
Enter fullscreen mode Exit fullscreen mode

create a new folders in /src named /lib/auth. Inside this auth folder create a file index.js

first lets import what we need and initialize our constants

import {getAuth, GoogleAuthProvider, signInWithPopup, onAuthStateChanged} from 'firebase/auth'
import {initializeApp} from 'firebase/app'
import { createContext, useContext, useEffect, useState } from 'react'


const app = initializeApp({
    apiKey: process.env.REACT_APP_apiKey,
    authDomain: process.env.REACT_APP_authDomain,
    projectId: process.env.REACT_APP_projectId,
    storageBucket: process.env.REACT_APP_storageBucket,
    messagingSenderId: process.env.REACT_APP_messagingSenderId,
    appId: process.env.REACT_APP_appId
})


const auth = getAuth()

const googleProvider = new GoogleAuthProvider()

const UserContext = createContext()
Enter fullscreen mode Exit fullscreen mode

We need to create a context provider so that we can access the user object in all components

/src/lib/auth/index.js

export const AuthProvider = ({children}) => {

    const [user, setUser] = useState()

    useEffect(() => {
        onAuthStateChanged(auth, (user) => {
            if(user) {
                setUser(user)
            } else {
                setUser(undefined)
            }
        })
    }, [])

    return (
        <UserContext.Provider value={user}>
            {children}
        </UserContext.Provider>
    )
}

export const googleSignIn = () => {
    signInWithPopup(auth, googleProvider)
}
Enter fullscreen mode Exit fullscreen mode

onAuthStateChanged creates an observer for changes to the user's sign-in state.

Now lets wrap out base level components with this AuthProvider

index.js

ReactDOM.render(
  <React.StrictMode>
    <AuthProvider>

      <App />

    </AuthProvider>
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Finally lets create a signInGoogle, a signOut and a useAuth function

export const useAuth = () => {
    return useContext(UserContext)
}

export const googleSignIn = () => {
    signInWithPopup(auth, googleProvider)
        .then(value => {})
        .catch(reason => {console.error(reason)})
}

export const signOut = () => {
    auth.signOut()
        .then(value => {})
        .catch(reason => {console.error(reason)})
}
Enter fullscreen mode Exit fullscreen mode

now in our App.js we can use these functions

import {googleSignIn, signOut, useAuth} from './lib/auth'

function App() {

  const user = useAuth()

  return (
    <div>
      {JSON.stringify(user)}
      <button onClick={(e) => {
        e.preventDefault()
        googleSignIn()
      }}>Sign in with google</button>
      <button onClick={(e) => {
        e.preventDefault()
        signOut()
      }}>Sign Out</button>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Full code here.

Discussion (0)