I am trying to redirect a user if they’re logged i...
# help
s
I am trying to redirect a user if they’re logged in on page load and I can’t for the life of me figure out how. I’ve been using
supabase.auth.user()
and
supabase.auth.session()
but often the page loads before the auth values are fetched and updated. How are you guys handling this?
The values are null initially but are quickly populated once Supabase checks that the user is logged in. If this function returned a Promise, none of this would be a problem!
s
Typescript, so maybe not the most helpful to you:
Basically I know the user hasn't been checked yet if the value is
undefined
. If it's
null
then they aren't logged in, if it's a truthy value then they've logged in
so I can subscribe to
_supaService.user$
anywhere (this is a service provided in root) and check the values to know what state the user is in
but I do agree that it's annoying that the user method isn't something you can wait for asynchronously and it only tells you the current state when you call it
Also if you do something like above in a non-root injected service, you're gonna wanna catch the subscription returned from
onAuthStateChange
so you can destroy it when needed so you don't have memory leaks
f
Are you using NextJS by chance?
Whoops I just read further down the channel before this was converted to a thread. I think the solution I've got in NextJS could work for you
basically the idea is that you have an api route which sets a cookie. then on page load (in the ssr call), you can check for the existence of that cookie and redirect to login if necessary
s
Great to know, thank you! Somehow I missed that the value is
undefined
before it's set. I thought it was
null
and that it stayed
null
when the user was logged out. I appreciate the example too—I'll give it a shot when I get the chance.
Thanks so much, I'll check this out as well.
Here's a link to the GitHub discussion I created a while back for those interested https://github.com/supabase/supabase/discussions/2315
s
It is null, my code sets a behavior subject value to undefined until a result from the server comes back using refresh session. This allows me to sort of wait until I know for sure