Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - “localStorage is not defined” error showing

I am trying to make my website SEO friendly with meta tags. I am implementing server-side rendering in my application. After this, I am getting the following error:

ReferenceError: localStorage is not defined.

Please help how to resolve it.

My package.json:

{    "main": "server.js",  "scripts": {   "start-dev": "NODE_ENV=development webpack -w & NODE_ENV=development node server.js",   "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC",  "dependencies": {   "axios": "^0.18.0",   "express": "^4.15.3",   "firebase": "^4.12.1",   "html2canvas": "^1.0.0-alpha.12",   "react": "^16.2.0",   "react-adsense": "0.0.5",   "react-dom": "^16.2.0",   "react-facebook-login": "^4.0.1",   "react-google-login": "^3.2.1",   "react-meta-tags": "^0.3.0",   "react-router-dom": "^4.2.2",   "react-router-match-as-promised": "^1.0.5",   "react-scripts": "1.1.1",   "react-share": "^2.1.1",   "react-slick": "^0.22.3"  },  "devDependencies": {   "autoprefixer": "^7.1.2",   "babel-core": "^6.25.0",   "babel-loader": "^7.1.1",   "babel-preset-es2015": "^6.24.1",   "babel-preset-react-app": "^3.1.2",   "babel-preset-stage-0": "^6.24.1",   "css-loader": "^0.28.4",   "extract-text-webpack-plugin": "^2.1.2",   "file-loader": "^0.11.2",   "postcss-loader": "^2.0.6",   "webpack": "^3.1.0",   "webpack-node-externals": "^1.7.2"  } } 

Meta Tags commonly used in all pages. Home.js

<code> import React, { Component } from 'react'; import axinst from '../common'; import {TabBox,TabBox2,TabBox3} from '../common/tabbox'; import Ads  from '../common/ads'; import SubscribeFrm from '../common/subscribefrm'; import MetaTags from 'react-meta-tags'; import AdSense from 'react-adsense'; import Loader from '../common/loader';  class Home extends Component {   constructor(props) {     super(props);   }    state = {     header:[],     otherSports:[],     wizztalk:[],     sports:[],     isProgress:'',     activeCat: '',     metaTitle:'',     metaDesc:'',     metaKey:''   }    componentDidMount(){       // axinst.get('/home')     this.setState({isProgress:true});     axinst.get('/home').then(response => {       this.setState({isProgress:false});       const header = response.data.data.Header;       const sports = response.data.data.Sports;       const otherSports = response.data.data.OtherSports;       const wizztalk = response.data.data.Wizztalk;       const metaTitle = response.data.data.metaTitle;       const metaDesc = response.data.data.metaDesc;       const metaKey = response.data.data.metaKeyword;       this.setState({header});       this.setState({sports});       this.setState({otherSports})       this.setState({wizztalk});       this.setState({metaTitle});       this.setState({metaDesc});       this.setState({metaKey});     }).catch(function (error) {       // console.log(error);       // console.log('error');     });   }    render() {     const hD = this.state.header;     const sport = this.state.sports;     return (     <div id="maincontent">         <MetaTags>           <title>{this.state.metaTitle}</title>           <meta name="title" content={this.state.metaTitle} />           <meta name="keywords" content={this.state.metaKeyword} />           <meta name="description" content={this.state.metaDesc} />           <meta name="og:description" content={this.state.metaDesc} />           <meta name="og:title" content={this.state.metaTitle} />           <meta name="og:image" content={process.env.PUBLIC_URL +"/images/logo.png"}/>         </MetaTags> </code> 
like image 212
Chander Shoor Avatar asked Sep 24 '18 07:09

Chander Shoor


People also ask

How do you fix localStorage is not defined?

To solve the "ReferenceError: localStorage is not defined" error, make sure to only use the localStorage object in the browser. The localStorage property is defined on the window object and is not available on the server - e.g. in Node. js or when using server side rendering with Next.

How do you set localStorage in React?

Saving data to localStorage in React is super easy: const [data, setData] = useState([]); useEffect(() => { localStorage. setItem('dataKey', JSON. stringify(data)); }, [data]);

How do you define local storage?

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.


2 Answers

When you're rendering on the server, you do not have a browser and thus you do not have access to all the APIs that the browser provides, including localStorage.

In JavaScript code that is running both on the server and on the client (browser), it is common practice to guard against with an if clause that checks if window is defined. “Window” is the root object provided by the browser for all the APIs that are provided by the browser.

Example:

if (typeof window !== 'undefined') {     console.log('we are running on the client') } else {     console.log('we are running on the server'); } 

In your case, you want to put your call to localStorage in such an if clause, for example:

if (typeof window !== 'undefined') {     localStorage.setItem('myCat', 'Tom'); } 
like image 177
Patrick Hund Avatar answered Sep 20 '22 05:09

Patrick Hund


This oneliner did it for me:

const checkout = typeof window !== 'undefined' ? localStorage.getItem('checkout') : null 
like image 38
Michelle Fernández Avatar answered Sep 23 '22 05:09

Michelle Fernández