useSession returns null for data in Next.js

Client side useSession form Better-Auth Client returns null:
const { data, error, refetch, isPending } = useSession();
console.log("SESSION DATA: ", data);
// logs SESSION DATA: null
const { data, error, refetch, isPending } = useSession();
console.log("SESSION DATA: ", data);
// logs SESSION DATA: null
Have no idea why. Can someone help me to figure it out? Does anyone had such issue?
Solution:
Are you sure the data isn't just pending? Because while it's pending you will get null.
Jump to solution
9 Replies
Glen Kurio
Glen KurioOP5mo ago
I set nextCookies plugin in BA Config as a last one in the array of plugins And I import createAuthClient from the right place:
import { createAuthClient } from "better-auth/react";
import { createAuthClient } from "better-auth/react";
Could you help, please ? @Ping
Solution
Ping
Ping5mo ago
Are you sure the data isn't just pending? Because while it's pending you will get null.
The Untraceable
The Untraceable5mo ago
How have you setup your auth.ts and auth-client? Are you sure you're logged in?
Glen Kurio
Glen KurioOP5mo ago
That's it. 🤦‍♂️ Thank you
FrancyMak
FrancyMak5mo ago
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
Ping
Ping5mo ago
If you want the session immediately, you can call .getSession instead of .useSession.
FrancyMak
FrancyMak5mo ago
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
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const router = useRouter()
const user = useUser()
const [isLoading, setIsLoading] = React.useState(true)

const { transcripts, setTranscripts } = React.useContext(GlobalContext)
const { transcript: currentTranscript, setTranscript } = React.useContext(GlobalContext)

const [onlyOwns, setOnlyOwns] = React.useState(!user?.isAdmin)
const [filter, setFilter] = React.useState('channelName')
const [keyword, setKeyword] = React.useState<string | null>(null)

const [page, setPage] = React.useState(1)
const [totalPages, setTotalPages] = React.useState(0)

useEffect(() => {
fetchArchive()
}, [page, onlyOwns, keyword, filter])

const fetchArchive = async (pageNumber = page) => {
try {
const response = await axios.get(
`/api/transcripts?page=${pageNumber}${keyword ? `&filter=${filter}&keyword=${keyword}` : ''}${
onlyOwns ? `&userId=${user.discordId}` : ''
}`
)
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const router = useRouter()
const user = useUser()
const [isLoading, setIsLoading] = React.useState(true)

const { transcripts, setTranscripts } = React.useContext(GlobalContext)
const { transcript: currentTranscript, setTranscript } = React.useContext(GlobalContext)

const [onlyOwns, setOnlyOwns] = React.useState(!user?.isAdmin)
const [filter, setFilter] = React.useState('channelName')
const [keyword, setKeyword] = React.useState<string | null>(null)

const [page, setPage] = React.useState(1)
const [totalPages, setTotalPages] = React.useState(0)

useEffect(() => {
fetchArchive()
}, [page, onlyOwns, keyword, filter])

const fetchArchive = async (pageNumber = page) => {
try {
const response = await axios.get(
`/api/transcripts?page=${pageNumber}${keyword ? `&filter=${filter}&keyword=${keyword}` : ''}${
onlyOwns ? `&userId=${user.discordId}` : ''
}`
)
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
Michael Morasch
Michael Morasch5mo ago
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
FrancyMak
FrancyMak5mo ago
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

Did you find this page helpful?