NextJS ReferenceError: document is not defined

Viewed 5234

I am making a NextJS app. I am using cookies to save access tokens returned from REST API. In login.js, cookies are being created successfully:

  document.cookie = `token=${res.data.result.accessToken}; path=/;`;
  

but when I access it in header.js :

if (document.cookie.split(';').some((item) => item.trim().startsWith('token='))) {
     SetAuth("true");
}

it says;

ReferenceError: document is not defined

Any reason, or any other way to save tokens and access them?

1 Answers

as Nextjs use SSR you don't access to document when code is being executed in server side running phase, you can do some checks to know if your code is being executed in browser, you can check solutions in this post.

as a fast answer you can check if you have access to window object first

if (typeof window !== "undefined") {
 // your code with access to window or document object here 
 }
Related