Home > OS >  Typecsript and NextJS how to check if "document" exists
Typecsript and NextJS how to check if "document" exists

Time:02-16

NextJS renders part of the code server-side. I can handle that. But I would need to check if cookies are set and here I run into problems. I tried:

!!document && !!document.cookie

and

document !== undefined && !!document.cookie

Each time I get the same error:

ReferenceError: document is not defined

I just want to make this clear, I do not want to render the component exclusively client side. The only thing I want to check is if document.cookie is defined or not :)

I am thankful for every answer that would help me solve this problem


UPDATE:

I accepted the first answer since it was the correct one. However, I realised my approach was wrong and solved it by explicitly checking the type of document:

typeof document !== 'undefined' && !!document.cookie

I guess I did not have enough coffee yet and I missed something pretty obvious.

CodePudding user response:

Next.js uses pre-rendering, so you should wrap any use of document in the useEffect hook as document is not available on the server. That way the particular code gets executed just client-side.

https://nextjs.org/docs/migrating/from-create-react-app#safely-accessing-web-apis

  • Related