Next.js Discord

Discord Forum

Avoiding hydration errors on client components that read cookies

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
I guess this is also a broader question about how to deal with any component that needs browser APIs:

how are you meant to handle a scenario where a client component's initial rendering results depends on a cookie value? This leads to a hydration error since you can't access the cookies via browser APIs on the backend, so the best you can do is just not attempt to read them and provide a blank string as the value or something. Then on the initial render on client the cookies do exist so the result will be different, thus hydration error.

How do people handle for this? does everyone just use useEffects and things to make sure that none of their components attempt to read from cookies on initial render?

also, is there some way I can just seamlessly switch between the serverside cookies function and browser APIs depending on where it's running?

2 Replies

@Sun bear There are 2 approaches
- use next/dynamic with ssr: false
- use client-only npm
@Sun bear Did you try ⬆️ ?