useSession returns null for data in Next.js
Client side useSession form Better-Auth Client returns null:
Have no idea why. Can someone help me to figure it out? Does anyone had such issue?
Solution:Jump to solution
Are you sure the data isn't just pending? Because while it's pending you will get
null
.9 Replies
I set nextCookies plugin in BA Config as a last one in the array of plugins
And I import createAuthClient from the right place:
Could you help, please ? @Ping
Solution
Are you sure the data isn't just pending? Because while it's pending you will get
null
.How have you setup your auth.ts and auth-client? Are you sure you're logged in?
That's it. 🤦♂️ Thank you
That's the thing, if i need the user session
in a client component
i will get null when the page mount, so that hook is useless in this way
or please tell us how to use it
If you want the session immediately, you can call .getSession instead of .useSession.
Yeah in a client component
This is my case, i think it's quite a common case, i have a sort of email reader which should give me the email list when the it mounts, but the user from useUser (bascially useSession > session.data.user) is null
with next-auth it was working fine because their useSession is immediate
but i recently switched to better-auth which is giving me this issue
the only way, from what i can see, is to fetch the session somewhere else and pass it as a prop
why nobody in the better auth discord has a solution for this
Never had this issue. Did you add the correct plugin for cookies in nextjs? https://www.better-auth.com/docs/integrations/next#server-action-cookies
and are you sure the endpoints for auth are even getting called? does your middleware maybe block the endpoints through the matcher? you can build a simple wrapper around the auth endpoints and check if they are triggering
Yes
Better solution for this, is to get the session from auth.api in your api route if you need some sort of data when the components mounts and you can't / don't want to wrap it