In reactjs and nextjs constructor getting Reference Error: localstorage is not defined In reactjs and nextjs constructor getting Reference Error: localstorage is not defined node.js node.js

In reactjs and nextjs constructor getting Reference Error: localstorage is not defined


On the constructor as well as componentWillMount lifecycle hooks, the server is still rendering the component. On the other hand, localStorage exists as part of the browser's Window global, thus you can only use it when the component is rendered. Therefore you can only access localStorage on the componentDidMount lifecycle hook. Instead of calling localStorage on the constructor, you can define an empty state, and update the state on componentDidMount when you can start to call localStorage.

constructor() {   super()  this.state = {    students: [],    student: undefined    token: undefined,    isLoggedIn: undefined  };}componentDidMount() {  this.login();  this.setState({    student: localStorage.getItem('student') || {},    token: localStorage.getItem('token') || "",    isLoggedIn: (localStorage.getItem('student' == null)) ? false : true  });}


As everyone already mentioned, NextJS runs both on client and server. On the server, there is no localStorage, hence the undefined error.

However, an alternative solution is to check if nextjs is running on the server before accessing the localStorage. ie

const ISSERVER = typeof window === "undefined";if(!ISSERVER) { // Access localStorage ...localStorage.get...}


I never touched nextjs but i guess its equivalent to Nuxt.js. So it does server side rendering while you try to access localstorage on the client side.

You will need to use componentDidMount() for this. Here an example

componentDidMount(){   localStorage.setItem('myCat', 'Tom');   alert("Tom is in the localStorage");}

EDIT:

Otherwise you could try with process.browser

if (process.browser) {   localStorage.setItem("token", token);}