'Why is setPersistence not working in Firebase?
I am trying to keep users signed in regardless of the page they are on until they choose to log out. I am trying to do this by initializing the firebase config on each page to have a persistence type of browserLocalPersistence. Unfortunately, the user is not currently staying signed in after the page is changed/reloaded. Where am I going wrong? There are no errors being produced.
import {
initializeApp
} from 'https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js'
// Add Firebase products that you want to use
import {
initializeAuth,
signInWithEmailAndPassword,
signOut,
setPersistence,
browserSessionPersistence,
browserLocalPersistence,
indexedDBLocalPersistence
} from 'https://www.gstatic.com/firebasejs/9.6.7/firebase-auth.js'
const firebaseConfig = {
apiKey: "xxx",
authDomain: "xxx.firebaseapp.com",
databaseURL: "https://xxx.firebaseio.com",
projectId: "xxx",
storageBucket: "xxx.appspot.com",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx",
persistence: browserLocalPersistence
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = initializeAuth(app);
console.log(app, auth);
auth.onAuthStateChanged(user => {
if (user) {
console.log('User logged in: ', user);
const navRight = document.getElementById('navRight');
navRight.innerHTML = `<a id="logout" href=".">LOGOUT</a><a href="../about/">ABOUT</a>`;
// Logout
const logout = document.getElementById("logout");
logout.addEventListener('click', (e) => {
e.preventDefault();
console.log('User logged out');
signOut(auth).then();
});
} else {
console.log('User not logged in');
}
});
const loginForm = document.querySelector('#login-form');
const loginButton = document.getElementById("login-button");
var identification = "";
var password = "";
// Login
loginForm.addEventListener('submit', (e) => {
console.log(1);
e.preventDefault();
var identification = loginForm['identification'].value;
var password = loginForm['password'].value;
var loggedIn = false;
console.log(2);
setPersistence(auth, browserLocalPersistence);
setPersistence(auth, browserLocalPersistence)
.then(() => {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return signInWithEmailAndPassword(auth, identification, password);
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
