accessing client side storage in next13 react server components

i'm trying out nextjs 13 and using their new routing. i have a page and loading component. i want to use localstorage/cookies/anything i can store on the client to get the user's session to get data in the page component. to do this i would have to switch to a client component which defeats the purpose. is there a workaround?
15 Replies
Leonidas
Leonidas•2y ago
You would have to store the local data on the server too. A big drawback :/ For such use cases a traditional client component sounds better
oa
oa•2y ago
how would you do that? i was thinking about storing a session token in localstorage to auth with it
Leonidas
Leonidas•2y ago
I would create a custom hook, that has the same api as useState. Lets call it useLocalStorageSynced. It will also have a simple key string as a prop parameter to identify it (local storage key). Internally it checks on the client the local storage for that key. It provides it to the app (useState), but also sends the value stringified to the server. That would be my goto implementation.
oa
oa•2y ago
how would you send data from a client to server component
Leonidas
Leonidas•2y ago
Since that is not possible i send this data first from the client to the server. Afterwards i can access the data also on the server on every future request. The data needs to be stored in the database for this. But for use cases where local storage is desired this feels wacky. A serverside session storage would be a better name for what i described.
oa
oa•2y ago
i dont get what you mean, the session is stored in the database but how will the server component get access to the session id
Leonidas
Leonidas•2y ago
useServerSession would make for a better hook name By calling prisma.serverStorage.findFirst({where: user: {id: session.id}}) A custom table named serverStorage with a relation to the user table is implicit in my previous pseudo code
oa
oa•2y ago
yes but for this you will need session.id where will you get that from in the server component
Leonidas
Leonidas•2y ago
From your auth provider, that is the job of it Next/Auth is popular here
oa
oa•2y ago
do server components have access to the req object?
Leonidas
Leonidas•2y ago
I prefer blitz Auth. But this is only a choice of the tool for the same job Else their purpose would be that of static html or not? Or atleast that of ISR
oa
oa•2y ago
i haven't seen any documentation about them passing the req object to server components though i might be wrong
Leonidas
Leonidas•2y ago
That suprises me, kind of defeats their purpose from what i thought
oa
oa•2y ago
okay so i tried console logging req and its empty
{ params: {}, searchParams: {} }
{ params: {}, searchParams: {} }
Leonidas
Leonidas•2y ago
Well then my implementation apparently wont work for server components One of the few times where php actually is better 😄
Want results from more Discord servers?
Add your server