T
TanStack5mo ago
foreign-sapphire

How to avoid hydration errors with conditional rendering based on auth state?

Hello! I am getting a hydration error because my auth state does not line up on the server and the client. I have posted my component. Basically my auth function really only gets the session on the client leading to this rendering to be out of sync between server/client how would i fix something like this?
No description
7 Replies
foreign-sapphire
foreign-sapphireOP5mo ago
line 35 is where i conditionally render the dashboard/sign up buttons and line 8 is where i'm getting the auth state from i guess a deeper question is also how would i go about isomorphically getting the session on the server and the client so that the SSRd page does load in correctly? is that the right approach?
flat-fuchsia
flat-fuchsia5mo ago
A very common patter is setting the user inside the router context on the server (by returning it from __root.tsx beforeLoad) and use useRouteContext hook to read the value in the navbar, it works in the server and in the client https://tanstack.com/router/latest/docs/framework/react/guide/router-context
Router Context | TanStack Router React Docs
TanStack Router's router context is a very powerful tool that can be used for dependency injection among many other things. Aptly named, the router context is passed through the router and down throug...
foreign-sapphire
foreign-sapphireOP5mo ago
how would i access users cookies on the server ? that’s my problem is im trying to set the user in the root beforeLoad however the server doesn’t have the cookie
suitable-rose
suitable-rose5mo ago
server can read cookies via getCookie
foreign-sapphire
foreign-sapphireOP5mo ago
is my approach even correct? how would i just use the return value of a hook in router context? (ive read the docs on RouterProvider but couldn't get it to work with Start)
curly-silver
curly-silver2mo ago
I'm assuming this calls the backend (whatever my backend is) to get user on every single page, right?
flat-fuchsia
flat-fuchsia2mo ago
yes, to avoid the request the most common pattern is using react-query and cache the value

Did you find this page helpful?