Henrique Ramos
Henrique Ramos

Reputation: 786

How i can access my window.localStorage in NextJs

I'm studying nextjs and I came across a problem, I'm saving a jwt in localstorage and I created a function to receive the component I want to return (the page), this function needs to check if there is a token in localstorage, if it exists it returns the component , if it does not exist it redirects the user. I've already made code similar to this in other applications (without nextjs) and the code runs fine but with the next I'm having the following error:

Server Error ReferenceError: window is not defined This error happened while generating the page. Any console logs will be displayed in the terminal window.

Basically I don't have access to the window. How can I access the window? Is there a better way to generate private routes in nextjs manually?

enter image description here

Here's how I'm doing to make it a private route on the desired component: enter image description here

Upvotes: 0

Views: 1220

Answers (1)

Sayog
Sayog

Reputation: 770

You have to check typeof window !== 'undefined' then run window.localStorage code as window is undefined in server so you are getting that error.

if(typeof window !== 'undefined'){
  window.localStorage.getItem('token')
  // all other localStorage must be wrapped with this is if statement check
}else{
 return
}

Upvotes: 1

Related Questions