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
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
how would you do that?
i was thinking about storing a session token in localstorage to auth with it
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.
how would you send data from a client to server component
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.
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
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
yes but for this you will need session.id where will you get that from in the server component
From your auth provider, that is the job of it
Next/Auth is popular here
do server components have access to the req object?
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
i haven't seen any documentation about them passing the req object to server components though i might be wrong
That suprises me, kind of defeats their purpose from what i thought
okay so i tried console logging req and its empty
Well then my implementation apparently wont work for server components
One of the few times where php actually is better 😄