Firebase-js-sdk: FR: please add function Auth.getCurrentUser() as a promise that will return current user or null

Created on 23 Jan 2018  Ā·  65Comments  Ā·  Source: firebase/firebase-js-sdk

  • Firebase SDK version: 4.9.0
  • Firebase Product: auth

Auth.currentUser object is unreliable to get user from persistence storage. If the authentication system could be pending and don't really have ensure finishing endpoint then you should have a promise for it

So I want to have promise function Auth.getCurrentUser() in addition to onAuthStateChange that would eventually return user but would return null if no user exist in persistence storage or user require sign in from expired token

auth internal-bug-filed feature request

Most helpful comment

You can easily implement that on your own with a couple of lines:

function getCurrentUser(auth) {
  return new Promise((resolve, reject) => {
     const unsubscribe = auth.onAuthStateChanged(user => {
        unsubscribe();
        resolve(user);
     }, reject);
  });
}

All 65 comments

Hmmm this issue does not seem to follow the issue template. Make sure you provide all the required information.

You can easily implement that on your own with a couple of lines:

function getCurrentUser(auth) {
  return new Promise((resolve, reject) => {
     const unsubscribe = auth.onAuthStateChanged(user => {
        unsubscribe();
        resolve(user);
     }, reject);
  });
}

@bojeil-google If the user does not signed in will that promise would ever fired for null?

And I think this function is really common enough to included in the SDK

Yes that promise will fire. onAuthStateChanged always triggers with the initial state even when it is null. That is what you care for here, the current state. After that is determined, you unsubscribe.

I see but anyway if it really just a couple line and will be the same for everyone so why it not be inside SDK. Did you not consider it useful?

And also that function would fire only one time at first call and will not fire again in second call am I right? What I want from getCurrentUser() function is consistently return null if it already checking in persistence storage, or return the actual current user after that

At least it should have a function like getPreparedAuthStated() or isPreparedAuthFinished

I have no idea what you mean by: " consistently return null if it already checking in persistence storage, or return the actual current user after that".

@bojeil-google If I don't misunderstand, the onAuthStateChanged in promise function you present will work only on the first call. If I call that function on the second time it will never return because the auth state never change again after that

This is not what I want from getCurrentUser(). I want this function to actively checking that user is not really signed in before. I want it to be promise just in case that firebase auth does not finish initializing yet, in that case the user was signed in before but firebase itself are not ready. So return promise is better solution

What I want is

  • If called when firebase auth preparation is not finished : return promise to wait

    • after preparation finished but user was not signed in before : resolve null from the promise

    • after preparation finished and user was signed in before : resolve currentUser from the promise

  • If called after firebase auth preparation is finished

    • but user is not signed in : immediately resolve null from the promise

    • and user is signed in : immediately resolve currentUser from the promise

I want this consistence behavior for getCurrentUser() function

But if I don't misunderstand, the function you present will never resolve if that function was called after firebase auth preparation is finished unless the user try to signed in

If I misunderstand above, which means onAuthStateChanged will always fire once whenever it get called for the current user without the need of signIn or signOut action. Then I would like to request that this behavior should be mentioned in the document

Please read the documentation, you presume some incorrect assumptions.
If we were to implement a promise that returns the current user, it will be done as I described.
onAuthStateChanged will always trigger every time it is set. It is super easy to test that.
If it is called while Auth is still initializing and loading state, it will wait for it to complete before resolving. If you call it after, it will still trigger immediately with the current user.

If you want some custom function or listener that triggers based on your own custom requirements, we provide all the APIs you need to build that.

If you are experiencing issues with the behavior of onAuthStateChanged listener, please file the bugs and we will make sure to address them.

@bojeil-google I know that if I call onAuthStateChanged before initializing and loading state it would be triggered. However I read the document and haven't seen mentioning about what happen if I register onAuthStateChanged after it finished initializing and loading state but the user is not signed in yet

I know that it would be surely be triggered whenever user would sign in by any means. But if user never sign in at all would it trigger that it change from null to null?

Why is that?

Is it changed from null as auth not initialized to null as user not signed in ?

And if I register onAuthStateChanged after finished initialized why it still trigger when user AuthState was not changed at all?

In the document

https://firebase.google.com/docs/reference/js/firebase.auth.Auth

I have seen the explanation only these

Adds an observer for changes to the user's sign-in state.

Prior to 4.0.0, this triggered the observer when users were signed in, signed out, or when the user's ID token changed in situations such as token expiry or password change. After 4.0.0, the observer is only triggered on sign-in or sign-out.

At this line

the observer is only triggered on sign-in or sign-out

is very pinpoint that if user not doing any signin/signout at all it should not be triggered just from registering the observer

Also in here is not mention about that too

https://firebase.google.com/docs/auth/web/manage-users

What document you think I should read?

@bojeil-google Do you have a link to the document you mention about this behavior?

This is the reference for onAuthStateChanged:
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged

This is the guide on how to use it:
https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed_in_user

Any time you call this listener after initial state has been determined, it will trigger with the current state (null if no user signed in, and with a user if a user is signed in). If you don't believe, then just try it out yourself.

@bojeil-google It not that I would not belief but it the API name itself is misleading so I got confused. I test it and it seem the real behavior is like you stated. But because it not mentioned in the document I don't know I should rely on it or not

That's why I said if I misunderstand then it should be documented about this behavior. Because the API name is "onAuthStateChanged" but it will also firing one time when the auth state not really changed

Fair enough. We should update the documentation and references to mention that. Thanks for pointing that out.

I will šŸ‘ this request, I just wasted a lot of time trying to find a method on the api to load the currently logged in user on page load before I found this issue. It needs to be mentioned that this will also load the user from the persistence if it is persisted.

Here is modified version of @bojeil-google function that can be used anytime to get a promise that resolves into current user or null.

let userLoaded = false;
function getCurrentUser(auth) {
  return new Promise((resolve, reject) => {
     if (userLoaded) {
          resolve(firebase.auth().currentUser);
     }
     const unsubscribe = auth.onAuthStateChanged(user => {
        userLoaded = true;
        unsubscribe();
        resolve(user);
     }, reject);
  });
}

I've šŸ‘ this request, too. As the Thaina, I also think the documentation about onAuthStateChanged is not clear about the discussed behavior, and even the API name itself is misleading. To me, it seems that an action from the user is needed in order to trigger the function, very much like the HTML onClick event.

@atishpatel I've tried that but it deosnt work for me :/

onAuthStateChanged is called when the user auth state changes and when the firebase.auth is first initialized.

Does anyone know if firebase.auth().currentUser caches the user, with or without persistence enabled. Or if requires a new network request API call everytime?

firebase.auth().currentUser caches the user regardless of persistence.

No idea... I'm using nuxt and have this as a pluggin:

// PLUGIN FILE
import firebaseConfig from '~/firebase'
import firebase from 'firebase/app'

if (!firebaseConfig) {
  throw new Error('missing firebase configuration file')
}

export default ({store, redirect}) => {
  if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig)
  }
  return firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      store.commit('firebase/setUser', user)
    }
  })
}





// VUEX STORE MODULE 

...


setUser(state, user) {
    state.user = user
    return this.dispatch('firebase/setProfileRef', state.user.uid)
  }


setProfileRef: firestoreAction(({ bindFirestoreRef }, uid) => {
    return bindFirestoreRef('profile', firebase.firestore().collection('profiles').doc(uid))
  }),
...

sometimes causes inf recursion šŸ™ƒ

bump. I'm finding many hours wasted on the auth state. I vote for a simple API the consistently gives us the user or null when we need it.

See, authStateChanged has a purpose, and therefore it can be used to workaround the fact that .auth().currentUser is not a promise and it's value is not trustable (because it depends on asynchronous tasks), it's purpose is to watch changes at the auth state. getCurrentUser, method that doesn't exists currently, has a different purpose: to simply get the current user despite how many changes happened at the application until now.

Dont take this wrong, please, but having methods implicates in having closed scopes of use, it's a basic pattern rule.

Either making it possible to use async .auth.currentUser or .auth().getCurrentUser().then would be desired implementation.

@zerobytes I just wrap it in a promise before calling it from other services.

function getUser() {
  return new Promise((resolve, reject) => {
    let user = this.firebase.auth().currentUser;
    return user ? resolve(user) : reject(new Error('No user signed in')); 
}

Hey @holmberd,
I understood what you did, but it has no point in having a promise if your action is not asynchronous,
What we intent to do with getCurrentUser() is having a promise which will await until firebase auth has actually finished the process of identifying the current user. This task happens asynchronously which is the reason why an already authenticated app can fail get firebase.auth().currentUser, as firebase auth has not yet finished the process of setting it.

@atishpatel Answer is more like what we need, and will do the job, but it's still a workaround.
Firebase SDK should have it as a promise.

What we intent to do with getCurrentUser() is having a promise which will await until firebase auth has actually finished the process of identifying the current user. This task happens asynchronously which is the reason why an already authenticated app can fail get firebase.auth().currentUser, as firebase auth has not yet finished the process of setting it.

I haven't seen any such failures occur and therefore can't confirm. But it does look like there is a fair share of ambiguity in regards to the API usage in general.

As I see it getCurrentUser is only guaranteed to be set after a firebase.auth().onAuthStateChanged event when a user has signed in, or in the resolved promise of firebase.auth().signIn*(provider). Where the latter is more useful if you are checking if the signed in user is a new user additionalUserInfo.isNewUser.

For me onAuthStateChanged gate-keeps any services relying on the signed in user state and maintain the asynchronous flow.

@holmberd I guess you might not know but, firebase library has an initialize duration in the loading time that, even user have been logged in and even have persistent logged in data stored in the local session, the currentUser would still be null until firebase system finish initialized itself

And this issue was voicing that, we don't really want a long term listener for the gate-keeps functionality you talk about. We want just a Promise or a Thenable to be that kind of gate-keep in the async function. We just want to call await getCurrentUser() and if it is null we then just show the logged-in button or launch the redirect flow. But we just need to call it one time and don't want to have it keep listening. So why we need to have it as listener that we need to unsubscribe by ourselves? It make our code unnecessary more bloated

@Thaina I have not experienced that issue. I initialize firebase before initializing any services depending on it. Could you show me an example of such behaviour to test?

@holmberd You can just read from the doc

https://firebase.google.com/docs/auth/web/manage-users

The recommended way to get the current user is by setting an observer on the Auth object:

By using an observer, you ensure that the Auth object isn't in an intermediate state—such as initialization—when you get the current user. When you use signInWithRedirect, the onAuthStateChanged observer waits until getRedirectResult resolves before triggering.

It's always mentioned since the beginning

ensure that the Auth object isn't in an intermediate state—such as initialization

@Thaina I see, yes I'm aware of this behaviour. I don't see the problem to be honest.

@holmberd The problem lies in this code

function getUser() {
  return new Promise((resolve, reject) => {
    let user = this.firebase.auth().currentUser;
    return user ? resolve(user) : reject(new Error('No user signed in')); 
}

Your code does not ensure that the current user aren't exist. Because if we call your code when the auth object still initialize it will just resolve null even the user has been logged in already. Which is the point of this issue and the request of people

Simply put, you don't see the problem and don't have a problem with this behaviour. But other people include me did. We need a getCurrentUser() as a promise function instead of .currentUser

@Thaina If you don't take the asynchronous nature of the library in consideration when calling the API and setting up your services, then yes you will run into these kinds of problems.

The code examples provided by bojeil-google and atishpatel will do what you want.

@holmberd I think you misunderstand everything in this issue

Promise is asynchronous in nature

It was this library that expose currentUser field without considering asynchronous nature of itself

This library actually should consider its own asynchronous nature. And so it should provide getCurrentUser() that would return Promise<User> which will be asynchronous

Any news?

I faced this issue too. When already logged in user refresh page the observer onAuthStateChanged returns null, and after 1-2 seconds fired one more time with logged user info.

But when in fires first time, my code decide that user should be redirected to login page.

What can you guys advise on such behavior?
Wait 1-2 seconds before listen onAuthStateChanged?

I think it is not a proper solution...

@proof666 As @bojeil-google mentioned: 'If it is called while Auth is still initializing and loading state, it will wait for it to complete before resolving. ' If you have a logged in user, refreshing the page should only trigger the listener once with that user. I tested myself and verified the behavior.

Seems like this is a whole lot more complex than it needs to be, Can't it be a sync read of the indexDB? Could that really be that slow?

@QuantumInformation There was a lot more preparation need to be done in firebase system before it could return proper user. I don't know what they kept in indexDB but I guess it is not a complete userdata. And if the system was online the user will most likely expect the fresh userdata

This used to work, but now it never fires (sorry if this is of topic)

https://github.com/QuantumInformation/svelte-fullstack-starter/blob/master/src/stores/firebaseUserStore.js#L38

const unsubscribe = firebase.auth().onAuthStateChanged(user => {
            userLoaded = true;
            unsubscribe();
            resolve(user);
        }, reject);

Now the app just doesn't do any network requests locally, any idea what could have happened? No errors either. the indexDB looks like this.

image

Any time you call this listener after initial state has been determined, it will trigger with the current state (null if no user signed in, and with a user if a user is signed in). If you don't believe, then just try it out yourself.

Actually, I've a signInWithCustomToken enabled with LinkedIn OAuth and I've done

console.log(firebase.auth().currentUser);

And I get null first and just a few seconds later, I get the user object. This is when I've already signed in. And this behavior is consistent. I get null and then after a few seconds, the user.

Same behavior with the authStateChanged as well. There's a delay which we cannot control.

If firebase.auth().currentUser were a promise, I could do:

showLoader();
firebase.auth().getCurrentUser().then(function(user){
  if(user) stopLoader();
  else redirectToLogIn();
});

Now, it ain't possible.

My solution for this topic, a bit ugly but it works like a charm on my side :D

  async _fetchLoginStateWithWaitingUntil4Sec() {
    // AuthCheck, Fire on load the app into the browser
    // check userinfo every 250ms until 4000ms passed
    const waitMSec = 250
    const loopMax = 4000/waitMSec
    for (let i=0; loopMax > i; i++) {
      console.log(`_fetchLoginStateWithWaitingUntil3Sec: ${i}`)
      const user = firebase.auth().currentUser
      if(user) {
        console.log(`_fetchLoginStateWithWaitingUntil3Sec: user:`, user)
        return user
      }
      await this._sleep(waitMSec)
    }
  }

  async _sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec))
  }

currentUser will be fetched around 1500ms. (of course it depends on the network conditions)

@proof666 As @bojeil-google mentioned: 'If it is called while Auth is still initializing and loading state, it will wait for it to complete before resolving. ' If you have a logged in user, refreshing the page should only trigger the listener once with that user. I tested myself and verified the behavior.

@wti806, You can see in @AmitJoki demo that it is not as @bojeil-google mentioned.

Everyone who encountered a problem is trying to tell about this. But those who have not encountered the problem sacredly believe in the documentation and refuse to believe in any arguments. Instead, they suggest wrapping the synchronous method in a promise (what does it change?)
It looks weird for a library of "google"-level.

Probably the problem is reproduced only under certain conditions, for example, when the page loads too quickly and the firebase does not have time to initialize. If you set a timeout of at least 1 second, the problem stops reproducing. So when your app starts to render when firebase already initialied you does not have any problems. But some apps start to render too fast, when firebase does not initilized yet <--- here is the problem.

Firebase Auth persists the data in "IndexedDB", additionally every time the app is initialized for the first time it makes a call to the api of "googleapis.com/identitytoolkit", I suppose that it is a way to verify that the information persisted in the browser be valid. Until the answer is complete we will have that currentUser will remain "null", Although the user has already logged in previously.

@bojeil-google, I would like to find some help in the documentation to handle this problem.

After spending a few hours/days on these issues, I think I understand some of the frustration. I also understand why wrapping currentUser doesn't really make any difference. Let me try to rephrase the problem from a different point of view.

  1. currentUser is poorly documented. It doesn't mention the fact that this value can be null during initialisation.
  2. onAuthStateChanged is poorly documented. It doesn't mention the fact the observer will be called at least once, after initialisation.
  3. However, there are other docs that provide more details for these methods. So unless you read all documentation carefully you're in trouble.
  4. Given that the recommended approach to get current user relies on onAuthStateChanged, it is not clear what could be a valid use-case for currentUser. There is no API that tells us when initialisation has finished, so it is not possible to know when it is safe to use currentUser. Maybe this method should get removed completely from the API?
  5. Not really related to this topic, but I wish the documentation would provide more information about the relation between onAuthStateChanged and getRedirectResult. It seems that onAuthStateChanged might wait to getRedirectResult to get resolved; but how do we know if we need to call getRedirectResult? Does error of getRedirectResult get delegated to onAuthStateChanged error parameter? etc.

@gamliela Very appreciate your understanding but I would like to add that onAuthStateChanged has its own usage and pattern. It was designed to be used in reactive styled application, such that when you have logged in profile on top of the page, you could let it listened and change UI immediately when user change their logged in account and status

However, in many situation when our app don't really need to be reactive, we just need to check a currentUser once and continue doing other things. onAuthStateChanged just become friction in async/await code

So IMO, the actual complete solution is to provide both API for covering each situation. And should deprecate direct currentUser while promote getCurrentUser() instead

I totally agree with @Thaina. The issue here is mixing a runtime event subscriber like onAuthStateChanged with a one-time event handler for _auth state initialised_ that is only required at application startup.

Handling each of those events requires totally separate logic and as such, should be facilitated by separate methods.

@Thaina and @philBrown I actually support that view. I'm sorry it wasn't clear from my earlier comment. I can't see a lot of value in a synchronous version of getCurrentUser. While obtaining current user can be done technically using onAuthStateChanged, it's not ideal in terms of developer experience. A better solution would be to replace it with asynchronous getCurrentUser (which will guarantee to resolve after initialisation).

Another approach could be to introduce another observer like onAuthStateInitialised. This can serve other needs except fetching the current user. Then you could do something like:

onAuthStateInitialised(() => console.log(app.auth().currentUser))

@gamliela Well, that I was not being clear on my side. I just mention that I would like it to be getCurrentUser as a promise so it actually being asynchronous

Currently now we don't have getCurrentUser function at all, we only have currentUser field

I'm having this intermittent issue as well forcing a user to login when they shouldn't have to. Agree getCurrentUser would be more deterministic.

For those of you using React, this hooks provide a loading boolean to indicate whether the authentication state is still being loaded: https://github.com/CSFrequency/react-firebase-hooks/tree/master/auth#useauthstate

I really appreciate the people above explaining the problem in detail and exploring possible solutions. I also wasted a few hours on this. While wrapping onAuthStateChange in Promise technically works, it is not the correct solution.

Either add an asynchronous getCurrentUser() method, or if you want to keep the currentUser thing synchronous, then add an asynchronous isAuthInitialised() method to let us check whether the initialisation has completed for sure.

Many thanks in advance!

Filed b/161733272 for internal tracking.

What about this?

function getCurrentUser = () => {
  return new Promise((resolve, reject) => {
    const currentUser = firebase.auth().currentUser
    if (currentUser) resolve(currentUser)
    else {
      const unsubscribe = firebase.auth().onAuthStateChanged(user => {
        unsubscribe()
        resolve(user)
      }, reject)
    }
  })
}

If the cached user is valid then just resolve quickly with it, and if not set the observable to wait for valid user or just confirm user log out

In angular this solution works for me:

import { first } from 'rxjs/operators';

public async getCurrentUser(): Promise<firebase.User> {
    return await this.afAuth.authState.pipe(first()).toPromise();
}

I wait for firebase to complete authentication using authState.

@avolkovi can I attempt to add async to sdk if you busy with other stuff ?

@harshshredding yes, you're more than welcome, thanks! Please assign myself and @bojeil-google to review your PR once ready.

Simply sharing -- in the hope that someone will find it useful :
this is how I use the promise version of getCurrentUser in my workflow. I import the below file called Firebase.js :

import * as firebase from 'firebase';
let firebaseConfig = {
   ...
};
firebase.initializeApp(firebaseConfig)
export const auth = firebase.auth()
export const getCurrentUser = () => {
    return new Promise((resolve, reject) => {
        if (auth.currentUser) {
            resolve(auth.currentUser);
        }
        const unsubscribe = auth.onAuthStateChanged(user => {
            unsubscribe();
            resolve(user);
        }, reject);
    });
}
export default firebase;

Also for me, the two nulls behaviour of .currentUser was a friction when getting started with Firebase. Something like 2 days lost because of it, altogether, but once one has it solved, the problem kind of fades away. For newcomers, this is certainly worth considering.

Two points:

  1. The .onAuthStateChanged ’s job is not only to inform once a person has logged in. It also informs about log-outs, and therefore cannot be 1:1 replaced with a promise.

Other than that, I think new JavaScript APIs should be Promise-based.

  1. @Thaina was not seeing a use case for the syncrhronous .currentUser. There kind of is. In my app, for Vue components where I know that the user has logged in, and is not changing, I can use it for getting user info. But also this feels a bit cheating, since it embeds something we just know about the app behaviour in between the lines. I’d likely prefer making it explicit, e.g. passing the user as a property. I certainly won’t cry after the synchronous version.

To me, the main point in this issue is @gamliela ’s comment from Apr 27th about the documentation.

@akauppi I am not sure how point 1 relates to the earlier suggestion :

export const getCurrentUser = () => {
    return new Promise((resolve, reject) => {
        if (auth.currentUser) {
            resolve(auth.currentUser);
        }
        const unsubscribe = auth.onAuthStateChanged(user => {
            unsubscribe();
            resolve(user);
        }, reject);
    });
}

The return value makes sense even when the user logs out.

Also for me, the two nulls behaviour of .currentUser was a friction when getting started with Firebase. Something like 2 days lost because of it, altogether, but once one has it solved, the problem kind of fades away. For newcomers, this is certainly worth considering.

Two points:

  1. The .onAuthStateChangedļæ½ ’s job is not only to inform once a person has logged in. It also informs about log-outs, and therefore cannot be 1:1 replaced with a promise.

Because that was not the use case needed around getCurrentUser I propose. We just want to know the immediate state of user logged in for current task, not to listening for it to changed. And if user are not logged in then it should return null

  1. @Thaina was not seeing a use case for the syncrhronous .currentUser. There kind of is. In my app, for Vue components where I know that the user has logged in, and is not changing, I can use it for getting user info. But also this feels a bit cheating, since it embeds something we just _know_ about the app behaviour in between the lines. I’d likely prefer making it explicit, e.g. passing the user as a property. I certainly won’t cry after the synchronous version.

I don't think anyone should ever rely on that because you really cannot be ensure that the currentUser was null because user are not really logged in, or user actually logged in but the sdk just not finish initialization

No, you should always rely on promise based. Because that field actually unreliable

Hello, everybody! How to check if a user can be authorized or not? If the user is not logged in, then render the application immediately, otherwise render the loading window and wait until the onAuthStateChanged event occurs. How to implement this behaviour? Thanks!

In general, issues are for bug reporting and feature requests, and we recommend support or Stack Overflow or other forums for help with usage but:

One common pattern is to set some local variable named user to undefined or some other state, then call onAuthStateChanged and in the callback, set user to whatever it returns, so there are 3 states.

If it is:

  • undefined or whatever you initialized it to, that means the check hasn't completed (you might render a loading indicator)
  • a Firebase User - the user is logged in (you might show authorized data)
  • null - that means the check came back and the user isn't logged in (you might show a screen asking them to log in)
const getCurrentUser = firebase.auth.getRedirectResult().then(() => firebase.auth.currentUser);

should achieve what you are looking for @Thaina.

const getCurrentUser = firebase.auth.getRedirectResult().then(() => firebase.auth.currentUser);

should achieve what you are looking for @Thaina.

I don't think getRedirectResult would always be activated unless the page is loaded from the redirection login flow

Was this page helpful?
0 / 5 - 0 ratings