Reputation: 15
I'm using firebase in my next.js app to login. My login works but logs out every time a user changes paths inside the site. Once logged in, the user is redirected to the front page with path=/ if a user changes paths to path=/question/page firebase immediately logs them out but their session cookie has not expired. I would like to use the session cookie to keep a user logged in until it expires no mater where they navigate on the site. I am not about to use the package firebase-admin because it keeps crashing my next.js site. I can only use the regular firebase package which includes firebase.auth() along with js-cookie package. Here is the code I am using to set my cookie:
componentDidMount() {
let user = firebase_auth.currentUser;
console.log("User: ", user);
if (user) {
this.setState({user_logged_in: true});
return firebase_auth.currentUser.getIdToken(true).then(function (token) {
Cookies.set('__session', token, {expires: 7});
})
}
else {
this.setState({user_logged_in: false})
}
}
How would I be able to use the session cookie being called in the code above so that my users aren't being logged out every time they navigate to a new path?
Thanks for your help in advance!
Upvotes: 0
Views: 1534
Reputation: 599001
Firebase Authentication SDKs automatically persist the user state between page/app reloads, and try to restore that state upon the restart.
The most likely cause of your problems, is that Firebase is still checking whether the authentication state is valid when you access firebase.auth().currentUser
.
In that case, the solution is to use an auth state listener:
componentDidMount() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
this.setState({user_logged_in: true});
firebase_auth.currentUser.getIdToken(true).then(function (token) {
Cookies.set('__session', token, {expires: 7});
})
} else {
this.setState({user_logged_in: false})
}
});
}
Upvotes: 0