TanStackT
TanStack2y ago
3 replies
popular-magenta

Prefetch/hydrate using session token from nextjsAuth

Hi,
I'm trying to understand a concept about the prefetch and hydration of the data when I need to use a session token to add it to the Authorization header. I'm using nextjsAuth to handle my sessionToken and I have two possible cases to get it in my nextjs app (First case I'm in a serverComponent and call getServerSession to retrieve the token. Second case I'm in a clientComponent and I need to call useSession to get the current session).

export const getUserInfo = (clientSession?: CustomSession) => {
return queryOptions({
queryKey: ["userInfo"],
queryFn: async (): Promise<IUserInfoResponse> => {
let session = null;
if (isServer) {
session = (await getServerSession()) as CustomSession;
} else {
session = clientSession;
}

This is a snippet of the logic I was thinking. If I'm in a serverComponent I simple call getServerSession inside the query Function. But if I 'm in a ClientComponent I need to pass the session as a prop because useSession is a hook and can't use it inside the query function directly.

So my main questions are:
-> Since I'm using always the same key is this data always prefetched in the server side and is immediately available in the client side?
-> Is this approach correct or I should have done this in another way?

Thanks in advance.
Was this page helpful?