Best way to get authenticated user on client side
Hi all,
Trying to understand what is the best way to access authenticated user in my app. (using nextjs 15 and supabase) in client components.
I thought having a context would be a good idea, but I could not get "onAuthStateChange" to work properly. My context works initially but does not update between logins.
What is the best way to access current user in client components?
Option 1: Getting the user in a useEffect and updating local state?
Option 2: Having a context and wrapping the app with it so all client components can access it.
7 Replies
Out of curiosity, why not get the user on the server?
You can pass whichever information you need to the client 🤷♂️
You can use a state manager like mobx, then in any components you want to get the user, you do something like:
This is the way I structure most of my code, and it helps to abstract the business logic elsewhere, and very maintainable also.
@DevsrealmGuy how do you handle user changes in state manager ? Eg login logout
I have so many client components I would not want to prop drill
Pass it to one client component which contains a context?
In the AuthStore, I am doing something like:
The in the logout component, I do something like:
It is as simple as that, anything authentication, login/logout, etc is placed in the AuthStore, if you have say a project table, I place the logic in a ProjectStore, something like that
The cool thing about mobx though is that it can auto detect all your changes and propagate them out to where they are being used. So, useEffect isn't needed most of the time. It takes getting used to though, but once you get a hang of it, it is very cool
Makes sense. I will try it, thanks
@DevsrealmGuy ohhh your implementation is a lot easier to handle as everything in one place.
I wonder what is the supabase suggested way of handling this
Yeah, it is a Domain Service encapsulation and well, there is no supabase way of handling this, what works for everyone is different you know 😉