简体   繁体   中英

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?

在此处输入图像描述

Here's how I'm doing to make it a private route on the desired component: 在此处输入图像描述

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM