Next.js Discord

Discord Forum

`document is not defined` in client component

Unanswered
Oak shoot sawfly posted this in #help-forum
Open in Discord
Oak shoot sawflyOP
Hello. I have some code that I want to execute before React renders (changes a CSS variable). For that I'm using document.documentElement.style.setProperty

This works well, the frontend is doing what I expect, but for some reason in my terminal I get document is not defined, despite this particularly component having the 'use client' directive.

If I wrap the code in type of window !== 'undefined', the server side error goes away, but the frontend then throws a warning in the browser console

Warning: Extra attributes from the server: style

2 Replies

If you want to execute it before React renders, inject a script with the <script> tag.
When you put some code in useEffect, it is only executed after hydration.
When you put some code in the component, it will be pre-rendered on the server, causing the error above.

Whenever possible, use the solution suggested by joulev