I really can't figure out what Next.js have for plan to make cookies work in client components. The current docs they have for cookies is not compatible with client components.
In server components, you can read and set the cookies using server actions. With client components, you can set them with server actions, but it doesn't look like you can read the cookies. Trying to use cookies().get(name) results in the error below.
You're importing a component that needs next/headers. That only works in a Server
...
Component but one of its parents is marked with "use client", so it's a Client Component. One of these is marked as a client entry with "use client":
./app/client/hooks/useCookies.ts
./app/client/components/SomeComponent.tsx
Of course, you can add a server actions to read the cookie, that I have tested to see that it works. But I refuse to mess up my code with async function handling and unnecessary server trips just to read a cookie that already lies right there in the browser.
I have also tried libraries, like cookies-next, which seems to be best maintained and working lib for Next.js cookies. That one works to read and set cookies in client components on client side.
The issue using that library is that the initial rendering flickers, since that library doesn't seem to be able to read the cookies server side with app routing. Even if I manually enable dynamic routing using Route Segment Config all cookies are undefined on the initial SSR request. It's first when I reach the client the cookies are found and read correctly. And with static rendering, cookies obviously cannot be read.
I have also tried setting the cookies using Next.js built in cookie system and then reading them with cookies-next library in my client components. Even using that solution, cookies are undefined on the initial SSR request.
Therefore I wonder, can anyone tell me if there is a way to make these two conditions work together when using Next.js app routing?
- Being able to read cookies in a client component directly from the browser (no server action)
- Being able to read cookies in a client component, on the server in the initial SSR request, when dynamic routing is enabled
Do I really have to read cookies in a server component and pass the cookie values down to client components as serialised values? Which also means that they will not be automatically updated when I set new values for the cookie.
I feel there is something working very wrong here, or I hope I have totally missed out something. Whole purpose with cookies is that you should be able to read them both client and server side.