T
TanStack•13mo ago
correct-apricot

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.
3 Replies
other-emerald
other-emerald•13mo ago
Piggy backing on this conversation as I ran into a similar issue. In the end, what I ended up doing was creating separate api file for server and client which I didn't like as it duplicates some similar functions. But in doing that way I utilized the import { cookies } from "next/headers"; for server and client side cookies in the client api to access a JWT session token I had set up used for auth headers. I'm thinking there is a better way but this way avoided any issues with importing client side functions on the server.
correct-apricot
correct-apricotOP•13mo ago
Hey mate thanks for sharing your point of view. But by doing that your page becomes dynamically rendered and not statically rendered right? (not saying that is a bad thing😅 ). I would say my doubt is: -> I have a queryFn ,function A , that can receive an optional prop. In the server component I don't pass that prop but in the client component I need to pass it. The returned data is the same in both cases. So can I use this approach and the function is only executed one time in the server side and in the other components where I call it using the useQuery this is all fetch and doesn't retrigger another request? Still would like to know the opinion of @TkDodo 🔮 if possible of course.
other-emerald
other-emerald•13mo ago
Hmm not sure what you mean @rasti about pages rendering. These are just function calls that the useMutation/useQuery hooks use but I could be missing something

Did you find this page helpful?