auth-js
auth-js copied to clipboard
onAuthStateChange should fire on initial load
Feature request
Is your feature request related to a problem? Please describe.
Currently it seems there is no deterministic way to know if a supabase session is done with initial loading.
If the user is signed out,auth.session()
will return null
and onAuthStateChange
won't fire. If the user is signed-in, auth.session()
will return null
, but then onAuthStateChange
will fire soon after with the session data.
Consider this code:
const sess = supabase.auth.session();
log("session event", sess);
changeSession(sess);
supabase.auth.onAuthStateChange((_event, session) => {
log("session event", _event);
changeSession(session);
});
A clear and concise description of what you want and what your use case is.
I need to load certain user history with knowledge of whether the user is signed-in or not. Yes it's possible to first fire assuming they aren't logged in, and then backtracking and firing again (once onAuthStateChange
is hit) saying actually they are signed in, but it forces me to fire changeSession a function which is resource intensive on my end twice.
Describe the solution you'd like
Either onAuthStateChange
should fire initially by default (how firebase auth works BTW), whether the user is signed in or not (perhaps a special INITIAL event) or should take a parameter {initial: true} to allow this behavior.
I would love to see something like this. I want to redirect the user to a login page if they are not signed in but I am having a hard time checking if they are actually signed in or not
Yes agreed. I'll tag this one with a "help wanted" - if anyone is interested, this can be implemented in gotrue-js after the recoverSession() fucntion call
We cannot send an event inside the constructor because the event listeners haven't been added yet
are there any news regarding the pull request? i didn't want to ask in the pull request.
This is the main problem in the supabase world
I am facing one more problem where the onAuthStateChange event is not triggering on logout.
this video by @dijonmusters Make User State Globally Accessible in Next.js with React Context and Providers shows the problem and workaround. But we need a solid solution.
I think the best approach is to represent the initial initialization state as a promise. The API would look something like:
const client = new GoTrueClient(options);
// any time later
await client.initialized();
if (client.user()) {
// signed in
} else {
// not signed in
client.signIn(credentials);
}
This avoids race conditions between the the construction of the client and adding event listeners, and allows one to check the initialization state at any point in the future.
I have created a pull request for this here: https://github.com/supabase/gotrue-js/pull/371
With v2 this is handled. getSession
will reuse the initial promise so any waiters on it will resolve properly.