Handeling multiple dependent states effectively server site and client site

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 fetch user before it. It’s using that to hide or show menu items.

page.tsx

  • has also a dependent query profile which also needs user to be fetched before it. This component will also use the user to redirect server side if the user is not logged in. But also prefetches the profile 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:

  1. 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 have children in the layout.
  2. 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 with const 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.