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
rival-black•2mo ago
GitHub
GitHub - notKamui/miniverso: Self-hostable grouping of mini web app...
Self-hostable grouping of mini web applications for everyday use - notKamui/miniverso
rival-black•2mo ago
i use better auth too
you can check how i did it
rival-blackOP•2mo ago
thank you @notKamui
apparent-cyan•2mo 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?rival-black•2mo 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
rival-black•2mo ago
and at the end of the beforeLoad, i pass it to the context by returning it