Reputation: 301
So i have this great react app using firebase auth and firestore. Everything working fine except
Whenever i reload the page while a user is already logged in... navbar links change for a second. Looks like app automatically re-login(re-auth) the user on every page reload. Why so? How to get rid of it? Some look-alike code sample
import React, {useState, useEffect} from 'react';
import {Switch, Route} from 'react-router-dom'
import firebase from 'firebase/App'
export const App = () => {
const [isAuth, setIsAuth] = useState()
const auth = firebase.auth()
useEffect(() => {
auth.onAuthStateChanged(user => {
if(user) {
setIsAuth(true)
} else {
setIsAuth(false)
}
})
}, [isAuth])
return(
<div className="App">
<Navbar />
<Switch>
<Route to="/signIn" component={Login} />
<Route to="/signUp" component={SignUp} />
<Route to="/signOut" component={SignOut} />
</Switch>
</div>
)
};
Upvotes: 6
Views: 5323
Reputation: 1090
I was having this problem too and I think Firebase's intended way of doing this is to use the FirebaseAuthConsumer... providerId
is null when awaiting auth status.
Compare this sandbox where the "not signed in" content is rendered for a split second before the signed in content, with this one where no render happens until Firebase has told us whether or not the user is signed in. Will need to press the "Sign in" button on first load and then refresh to test behaviour.
Upvotes: 0
Reputation: 301
Finally fixed it.
Reason it was happening bcoz firebase servers were verifying the user on each page reload which took some time and cause flickering in navbar for half a second.
Solution has three easy steps
Once logged in, store the user as boolean on local storage.
firebase.auth().onAuthStateChanged(user=>{
if (user) {
// store the user on local storage
localStorage.setItem('user', true);
} else {
// removes the user from local storage on logOut
localStorage.removeItem('user');
}
})
Check The user from local storage in navbar component
const userLocal = JSON.parse(localStorage.getItem('user'));
userLocal ? <SignedInLinks/> : <SignedOutLinks/>;
Remove user from local storage on logout
Upvotes: 9
Reputation: 21
@illiterate.farmer You are almost right. Actually you should only save a flag, isSignedIn=true or false
in the localStorage because saving the full user
object makes your app vulnerable to hacking very easily.
Any javascript function can access the localStorage and thus it will expose you tokens that can be used to impersonate as a genuine user to your backend system.
Upvotes: 2