How do I await *supabase.auth.user()* or *supabase...
# javascript
s
How do I await supabase.auth.user() or supabase.auth.session() inside an async function? The async function runs immediately on page load, but supabase.auth.user() returns null since it hasn’t retrieved the user object yet.
To be more specific, I’m using SvelteKit and I’m doing a basic redirect to the login page if the user isn’t logged in. This is all on the client side.
Copy code
javascript
export async function load() { 
  const auth = supabase.auth.user()
        
  // If user isn't logged in, redirect them back to the login page
  if (!auth) {
    return {
      status: 302,
      redirect: "/login"
    }
  }
        
  // If user is logged in, continue
  return {
    status: 200
  }
}
p
Copy code
const auth = await 
supabase.auth.user()
s
Sadly, this doesn’t work because supabase.auth.user() doesn’t return a promise
g
Auth.user does not issue any network activity. It just looks at the supabase object for user object. User must be signed in and set before you call it. If you want user value you have to wait for onAuthStateChange to go to “SIGNED_IN”.
s
Ok, thanks, that makes a lot of sense actually. So then, how would I block this async function until I know the auth/user state? Will onAuthStateChange fire the callback when it goes from not knowing the auth state to when the auth state is determined? Do I need to wrap onAuthStateChange in a custom Promise? There’s got to be a simple way to do this that I’m missing
g
from the docs on it: supabase.auth.onAuthStateChange((event, session) => { if (event == 'SIGNED_IN') console.log('SIGNED_IN', session) }) you put your handler there.
I use sveltekit and have a store for the user object and that code sets it, which then causes actions based on the store changing.
s
Ok, looks like I’ll have to wrap it in my own custom Promise then
That’s a awesome—I will definitely be using a store for this later on. However, it doesn’t solve the problem of the dashboard layout showing briefly even if the user is logged out
I’ll try wrapping supabase.auth.user() and onAuthStateChange and see how that goes
Thanks for the help!
g
Even starting up with a user in localStorage already signed in, it takes a bit of time for supabase createClient to get user setup.
s
Ok, that makes sense. I do wish the docs explained this a little more, especially that supabase.auth.user() can return a falsely value even if the user is actually logged in. But I’m sure the docs will improve as time goes on
g
Yeah, I figured it out by looking at how little that function did in the source.