I am using localStorage a lot on my authenticated components in my react application to get user details from local storage as well as storing them on login.
When I build my app, it throws ReferenceError: localStorage is not defined
.
I know this could be because node does not have access to localStorage and thus the error.
How can I solve the problem?
Here is an example of code I use in my component.
import React, {PropTypes} from 'react';
import AccountBasicInfo from '../components/AccountBasicInfo';
export class Account extends React.Component {
userBasicInfo(){
const user = localStorage.getItem('User') ? JSON.parse(localStorage.getItem('User')) :{};
const cashback = localStorage.getItem('cashback') ? JSON.parse(localStorage.getItem('cashback')) :{};
}
render(){
return(
<div>
<AccountBasicInfo theme="theme2" item={this.userBasicInfo.bind(this)()}/>
</div>
);
}
}
export default Account;
If you're used to working with client-only applications, it may come as a surprise that you can't access localStorage from the server. This is because localStorage is not defined on the window object, and Next. js performs a server render before the client render.
What is localStorage in JavaScript? localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. This means the data stored in the browser will persist even after the browser window is closed.
If you need to run the same, unmodified code on node, which does not have a native localStorage
implementation, you could consider using a shim such as node-localstorage.
You could also consider rewriting your code to use an alternative means of storing information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With