How to check if a user is logged in and then redir...
# help
y
How to check if a user is logged in and then redirecting to dashboard or login on page load?
supabase.auth.user()
doesn’t return a Promise, and returns null before it retrieves the session—making it hard to determine what the login state is.
n
Hello @yxsh! This thread has been automatically created from your message in #843999948717555735 a few seconds ago. We have already mentioned the @User so that they can see your message and help you as soon as possible! Want to unsubscribe from this thread? Right-click the thread in Discord (or use the ``...`` menu) and select "Leave Thread" to unsubscribe from future updates. Want to change the title? Use the ``/title`` command! We have solved your problem? Click the button below to archive it.
🆕 How to check if user is logged in?
j
@yxsh You probably want supabase.auth.session()
n
How to check if user is logged in?
g
You need to use onAuthStateChange() and have SIGNED_IN occur before running code needing a user.
j
Just note that onAuthStateChange doesn't trigger when a page first loads unless you call something like session
y
Ohh
Wait
g
Not sure how running session does anything different than user()...
Copy code
session(): Session | null {
    return this.currentSession
  }
Copy code
user(): User | null {
    return this.currentUser
  }
y
Copy code
ts
const session = supabase.auth.session()

        if (session) {
            if (session.user) {
                fetch(`http://127.0.0.1:5000/user_login?secret=bob&id=${session.user.user_metadata.provider_id}`).then(
                    async (resp) => {
                        const json = await resp.json();

                        const userr : UserInterface = {
                            name : session.user!.user_metadata.name,
                            id : session.user!.user_metadata.provider_id,
                            avatar : session.user!.user_metadata.picture,
                            inServer : json.inServer,
                            manager : json.manager
                        }

                        setUser(userr)

                    }
                )


            }
        }

        setLoading(false)

        // Listen for changes on auth state (logged in, signed out, etc.)
        const { data: listener } = supabase.auth.onAuthStateChange(
            async (event, session) => {
                if (session) {
                    
                    if (session.user) {
                        
                        const resp = await fetch(`http://127.0.0.1:5000/user_login?secret=bob&id=${session.user.user_metadata.provider_id}`)
                        const json = await resp.json();

                        const userr : UserInterface = {
                            name : session.user.user_metadata.name,
                            id : session.user.user_metadata.provider_id,
                            avatar : session.user.user_metadata.picture,
                            inServer : json.inServer,
                            manager : json.manager
                        }
                    
                        setUser(userr)

                }
            }
            setLoading(false)
        })
This should work?
So if there is a user it will occur before the code runs
j
You want to define onAuthStateChange before you run any of your other auth code
And it doesn't need to be conditionally set like you have above
Is this react?
g
I believe @jaitaiwan is correct though on just a page refresh, there is no signin event. The past few cases I've dealt with are people coming back from signin/signup redirect and there you get the state change. Unfortunately I'm drawing a blank and out of time tonight on just a normal page start with a user already in having a non expired jwt in localstorage.
j
There's a persistSession option for auth client which will store the details in localStorage. I'm not sure if the default is "true" or not
g
Yes it is default, but there is still a delay on startup.
j
I think from memory how I fixed it was to call auth.session() directly after doing the onAuthState callback. I assume that gotrue is "loading" until I get an event back.
g
I have it working in my svletekit code app, but don't have time, and don't remember, what I did...
y
Umm yes
g
This has some useful info. Basically if jwt is not expired then user returns the data without delay. But if null then you have to wait for refresh in on authstate...and an issue is mentioned, but don't have time to process it now. https://github.com/supabase/gotrue-js/issues/143#issuecomment-970288835
I believe what I did was have a localstorage "user" object, which I need anyway as I work offline and if that is there then I know if I get null from auth.user() then I have to wait for onAuthStateChange, if I don't have a user in my localstorage then I go to signin.
j
@garyaustin Any reason you didn't just use the localstorage key that supabase uses?
g
I have user profile type info I need offline so already had it from when I ported from Firebase. So I lucked out and never had the issue.