1

I have a simple login with firebase, but after a refresh it loses the user. The user gets stored in LocalStorage but on refresh it deletes it from there as well.

const loginform = document.querySelector('.loginform');
const email = loginform.email.value;
const password = loginform.password.value;


signInWithEmailAndPassword(auth, email, password)
.then(cred => {
    console.log('user logged in:', cred.user)
    loginform.reset()
    setPersistence(auth, browserLocalPersistence);
})

const auth = getAuth();
const user = auth.currentUser;

onAuthStateChanged(auth, () => {
const userplace = document.querySelector('.user')

if(userplace != null){
    if(user){
        userplace.innerHTML = `Welcome, ${user.displayName || user.email}`    
    }else {
        userplace.innerHTML = `Log in` 
    } 
}
})

and of course since there is no user it will show the "log in" text

Jaydendev
  • 123
  • 2
  • 14

1 Answers1

2

Firebase automatically persists and restores the user credentials on reloading the app/page.

But your code only handles the situation where the user explicitly signs in. To also handle the restore, have a look at the first code snippet in the documentation on getting the current user:

import { getAuth, onAuthStateChanged } from "firebase/auth";

const auth = getAuth();
onAuthStateChanged(auth, (user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    const uid = user.uid;
    // ...
  } else {
    // User is signed out
    // ...
  }
});

Minimal repro to check whether/show that this works: https://stackblitz.com/edit/auth-v9-restore. The first time you access this, it signs the user in anonymously. Then when you load it again, it restores that user.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Already tried this, but did not seem to work. Edited the question with the code. – Jaydendev Jun 08 '22 at 13:15
  • Yeah, it does not persist the auth token after refreshing the browser. – Dinesh Apr 09 '23 at 13:36
  • 1
    @Dinesh Can you try this StackBlitz: https://stackblitz.com/edit/auth-v9-restore?file=index.js? The first time you access it, it signs the user in anonymously. Then when you load it again, it restores that user. For me this works. – Frank van Puffelen Apr 09 '23 at 13:59