Maha Waqar
Maha Waqar

Reputation: 643

NextJS ReferenceError: document is not defined

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?

Upvotes: 6

Views: 12261

Answers (1)

Alireza Zarei
Alireza Zarei

Reputation: 314

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 
 }

Upvotes: 8

Related Questions