React Native - Firebase auth persistence not working
Solution 1
You don't need to set persistence. Firebase handles it for you by default. You just need to call this function to check whether user is logged or not:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log('user is logged');
}
});
This will not be triggered only if user has sign out or cleaned app data.
You can find more details in the official docs: https://firebase.google.com/docs/auth/web/manage-users
Hope it helps.
Solution 2
Make sure you do not restrict the 'Token Service API' in the console, with the API key you are using. I did not add the service to my key, and it logged me out every 3-4 hours, even with the right code suggested above.
Solution 3
Firebase
now recommends to use firestore
instead of realtime-database
and it manages offline persistence by default. It is clear in its documentation here
You just need to access the user through this code:
if (auth().currentUser !== null) {
console.log('User is logged in');
console.log(auth().currentUser.email);
props.navigation.navigate('Home');
} else {
props.navigation.navigate('Login');
}
This code will prop you to home screen if user is logged-in, even when you close the app. To clear the user's credentials, you manually need to sign-out the user using this code.
try {
auth()
.signOut()
.then(props.navigation.navigate('Login'));
} catch (error) {
Alert.alert('Error', error.toString());
}
You can also check this simple app (used react hooks
in it) for further assistance.
Related videos on Youtube
![Nouman Tahir](https://i.stack.imgur.com/uw9R3.jpg?s=256&g=1)
Nouman Tahir
I am a Passionate Application Developer with 3+ years of experience, I own a curious mind for writing codes powering Mobile Applications. My core expertise in Mobile Development are smooth UX, robust app back end and performance optimization. For mobile development, I have worked on Facebook API, Firebase, Cloud Integration, Optimized Sync Services, Persistence App Storage and Content Providers, App Animations, Bluetooth, Bluetooth LE, Robotic Apps, Voice Recognition and Narrators, Custom and many more. Other interests lie in developing autonomous linux based utility robots, working on robust HMI systems, contributing to IOT market and integrating everything with mobile smartphones. Always willing to dive in any sort of challenging problem that make me test my limits and add something new to my skill-set because I believe in life long learning. If you are looking for a developer who is good in communication and understands what a project means to owners, then you are definitely on the right profile, be sure to leave a message or contact me at [email protected] Thanks for stopping by.
Updated on June 06, 2022Comments
-
Nouman Tahir about 2 years
Firebase auth does not persist logged in user and everytime I refresh or reopen app I have to sign in again.
I have tried setting persistence to local and the callback does verify its set but the persistence is still no working
For setting persistence I am using...
//set auth persistence firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL) .then(function() { console.log("successfully set the persistence"); }) .catch(function(error){ console.log("failed to ser persistence: " + error.message) });
. . . For signing in I am using this code
firebase.auth().signInWithEmailAndPassword(email, password) .then((user) =>{ this.checkAccountStatus(user.uid, user.email); }) .catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; console.log(errorMessage) // ... });
And here is the code I am using to check login status...
if (firebase.auth().currentUser) { const currentUser = firebase.auth().currentUser; console.log("Signed in username" + currentUser.displayName); this.props.navigation.navigate('AppTab'); }else{ console.log("no user signed in"); this.props.navigation.navigate('AuthTab'); }
if there anything I am not doing right
-
bennygenel almost 7 yearscan you add which library are you using for firebase please?
-
Nouman Tahir almost 7 yearsI am using simple "firebase" package...."firebase": "^4.3.0",
-
-
Nouman Tahir almost 7 yearsI am using this method instead... firebase.auth().currentUser;...it doesnt work once the app refreshed using Cmd+R or restarted from simulator itself
-
soutot almost 7 yearsYou should replace your method to the one I provided. By the docs, that it the correct way to check whether a user is logged or not after the app has been closed. Let me know if worked.
-
Nouman Tahir almost 7 yearsjust tried it out, it didnt work and I wasnt expecting it to either, because according to docs, if user is already signed is .currentUser() is the right way to know whether status is signed in or out....see heading "Get the currently signed-in user" at firebase.google.com/docs/auth/web/manage-users
-
soutot almost 7 yearsI always used the code I provided in my componentWillMount on my login screen and never had problems. Even if user closes the app, when he opens again it checks if it's a logged user and navigate it to the home screen. Would you mind sharing where did you add it?
-
bojeil almost 7 years@soutot's answer is correct. LOCAL persistence is the default in react native and you should use
onAuthStateChanged
to detect that initially. -
Nouman Tahir almost 7 yearsit is in component did mount...and I did try onAuthStateChanged as well...in any case I have to relogin.. componentDidMount() { if (firebase.auth().currentUser) { const currentUser = firebase.auth().currentUser; console.log("Signed in username" + currentUser.displayName); this.props.navigation.navigate('AppTab'); }else{ console.log("no user signed in"); this.props.navigation.navigate('AuthTab'); } }
-
Nouman Tahir almost 7 yearsis it possible that its being caused because of iOS simulator...?
-
soutot almost 7 yearsI don't think so. I always used it and never had problems on simulators or real devices. Are you importing
firebase
orreact-native-firebase
in your project? Maybe this can be the truly issue. I know it works withfirebase
module. -
Nouman Tahir almost 7 yearsI am working with 'firebase' and not 'react-native-firebase' ... wanna stay as native as possible.... can you tell me you firebase and react-native package versions...might help
-
soutot almost 7 yearsThe current project I'm working uses Firebase 4.1.3 and RN 0.42.3
-
Nay over 6 years@soutot's answer is a better way to do. Here's official doc says: Note: currentUser might also be null because the auth object has not finished initializing. If you use an observer to keep track of the user's sign-in status, you don't need to handle this case. firebase.google.com/docs/auth/web/manage-users
-
9_Dave_9 over 4 yearsThis is because the object expires after an hour.. hence why the
auth().currentUser
.. apparently the tokenID is suppose to refresh automatically every hour.. but for React Native apps.. this isn't going to happen of the user has the app closed for that hour... -
Dacaramo about 2 years@soutot could you please explain how this will prevent Firebase from signOut after the user reloads the page? I don't really understand where do i have to put the
onAuthStateChanged()
call or why does even Firebase logouts the user after he reloads the page. Thank you!