T
TanStack5mo ago
inland-turquoise

How can I propagate user state across the backend and frontend?

I’m building an app using TanStack Start and Better-Auth. I want to fetch and access my user state or information during the beforeLoad or loader lifecycle hooks. I’ve seen examples where people put their user fetching logic in the beforeLoad of the __root layout, but when I do that, my page fails to load. Is this the correct approach to handle user state fetching? If not, what is the recommended way to propagate user state across both backend and frontend?
6 Replies
generous-apricot
generous-apricot5mo ago
GitHub
GitHub - notKamui/miniverso: Self-hostable grouping of mini web app...
Self-hostable grouping of mini web applications for everyday use - notKamui/miniverso
generous-apricot
generous-apricot5mo ago
i use better auth too you can check how i did it
inland-turquoise
inland-turquoiseOP5mo ago
thank you @notKamui
genetic-orange
genetic-orange5mo ago
im struggling to understand where you populate the user property inside the context. The $$auth middleware is only used in server functions. Do they populate it and because you're on ssr mode, have access to it in beforeLoad?
generous-apricot
generous-apricot5mo ago
see in __root.tsx beforeLoad, i use the queryClient to fetch the user thanks to userQueryOptions, which calls this server function https://github.com/notKamui/miniverso/blob/main/src/server/functions/user.ts
GitHub
miniverso/src/server/functions/user.ts at main · notKamui/miniverso
Self-hostable grouping of mini web applications for everyday use - notKamui/miniverso
generous-apricot
generous-apricot5mo ago
and at the end of the beforeLoad, i pass it to the context by returning it

Did you find this page helpful?