Next.js Discord

Discord Forum

NEXTJS authentication

Unanswered
Varun posted this in #help-forum
Open in Discord
The way I am managing a user's session is via a AuthUserContext wrapped around my layout. The problem with this is that if a user reloads, I lose all context. I want to also manage their session with cookies. How would I go about doing this?

import { createContext, useContext, Context } from 'react'
import useFirebaseAuth from '../app/authCreator';

const authUserContext = createContext({
    authUser: null,
    loading: true,
    signInWithEmailAndPasswordOut: async () => {},
    createUserWithEmailAndPasswordOut: async () => {
    },
    signOutOut: async () => {},
    googleSignIn: async () => {},
  });
  
  export function AuthUserProvider({ children }) {
    const auth = useFirebaseAuth();
    return <authUserContext.Provider value={auth}>{children}</authUserContext.Provider>;
  }
// custom hook to use the authUserContext and access authUser and loading
export const useAuth = () => useContext(authUserContext);

1 Reply

import { useState, useEffect } from 'react'
import { signInWithEmailAndPassword, createUserWithEmailAndPassword, onAuthStateChanged, signOut, GoogleAuthProvider, signInWithPopup} from 'firebase/auth';
import { auth } from '../../firebase-config';
import nookies from 'nookies';

const formatAuthUser = (user) => ({
  uid: user.uid,
  email: user.email
});
export default function useFirebaseAuth() {
  const [authUser, setAuthUser] = useState(null);
  const [loading, setLoading] = useState(true);

  const clear = () => {
    setAuthUser(null);
    setLoading(false); 
  };

  const authStateChanged = async (authState) => {
    if (!authState) {
      setAuthUser(null)
      setLoading(false)
      return;
    }

    setLoading(true)
    var formattedUser = formatAuthUser(authState);
    setAuthUser(formattedUser);
    setLoading(false)

    return {
      authUser,
      loading,
    };


  };

  // listen for Firebase state change
  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, authStateChanged);
    return () => unsubscribe();
  }, []);

  const signInWithEmailAndPasswordOut = async (email, password) => {
    try {
      const userCredential = await signInWithEmailAndPassword(auth, email, password);
      const user = userCredential.user;
      setAuthUser(formatAuthUser(user));
    } catch (error) {
      console.error("An error occurred:", error.message);
    }
  }



  const googleSignIn = async () => {
    const provider = new GoogleAuthProvider();
    try {
      const result = await signInWithPopup(auth, provider);
      const user = result.user;
      setAuthUser(formatAuthUser(user));
    } catch (error) {
      console.error("An error occurred during Google sign in:", error.message);
    }
  };


  return {
    authUser,
    loading,
    signInWithEmailAndPasswordOut,
    createUserWithEmailAndPasswordOut,
    googleSignIn, // Make sure to return the googleSignIn function
    signOutOut
  }

};


for context this is my authcreator