I have been looking everywhere for a solution but cannot find help or a solution anywhere. I hope someone will be able to help me with my problem.
I have the following setup:
| App
|-- Layout
| |-- Navbar.tsx (Server Side) - Needs `user` and `userData`
| | |-- DesktopMenu.tsx (Server Side) - Needs `user` and `userData`
| |-- {children} -> page.tsx (Server Side) - Needs `user` to redirect if not logged
| | | | <Component>.tsx in page.tsx (Client Side) - Needs `profile`
Navbar.tsx
- has a dependent query
userData
so I need to fetchuser
before it. It’s using that to hide or show menu items.
page.tsx
- has also a dependent query
profile
which also needsuser
to be fetched before it. This component will also use theuser
to redirect server side if the user is not logged in. But also prefetches theprofile
state to provide it to a client side component which needs it to show the data.
<Componoent>.tsx
- needs the
profile
state to show the data. So I prefetch it on the server side page.tsx component.
So I see two problems:
- Two server components need the same state to load another state. But
const user = await queryClient.fetchQuery({
would not provide it to the other server component, it will also not provide it to the client side component. Passing it down as a prop would also not work as I havechildren
in the layout. - I use a state to validate something on the server as well as the client so they need to be in sync. I’m confused as the docs say you should not do that. But isn’t it better to redirect a user on the server side if he is not authenticated? So I want to use
await queryClient.prefetchQuery({
to make it available on the client but as I need the state on the server I can’t use it. Therefore I would need to go withconst user = await queryClient.fetchQuery({
but this would not make it available on the client side.
My goal is to fetch things only once. And keep states in sync between the server and the client.