I am using firebase web sdk without React. I have 4 pages in my application. I am using express js in for each pages to send html file of that route.
I have a file called common.js
in which I defined methods that will be shared by all pages. In the same file I defined a method to act on auth changed is as following:
import { getAuth } from 'firebase/auth';
const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth(firebaseApp);
const handleOnAuthStateChanged = (user) => {
if (auth.currentUser === null || auth.currentUser !== user) {
window.location.replace('/login');
} else {
window.location.replace('/home')
}
}
export = {
auth, handleOnAuthStateChanged
}
On each page I first call handleOnAuthStateChanged()
, and it is also called after successful login. I want to persist the auth so I came across setPersistence()
, so I used it in login.js
and is as follows:
import { browserLocalPersistence, browserSessionPersistence, setPersistence, signInWithEmailAndPassword } from 'firebase/auth';
import { auth, handleOnAuthStateChanged } from './common';
document.getElementById('btnSignin').addEventListener('click', async (e) => {
e.preventDefault();
try {
const form = document.querySelector('form.formLogin');
const email = form.email.value.trim();
const password = form.password.value;
await setPersistence(auth, browserLocalPersistence);
await signInWithEmailAndPassword(auth, email, password);
handleOnAuthStateChanged(auth.currentUser); // here auth will retrieve the new logged in user
} catch (e) {
console.error(e);
}
});
If I use onAuthStateChanged()
on other pages my user is null then I am stuck in a loop.
Am I missing something?
CodePudding user response:
Firebase automatically persists the auth state on most browser environments, and restores it on app/page reload. To detect this restore of auth state (and other auth state changes) you will need to register an auth state listener with the SDK as shown in the first code fragment 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
// ...
}
});
Most of the code of your handleOnAuthStateChanged
can probably go into this handler.