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:
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');
}
This oneliner did it for me:
const checkout = typeof window !== 'undefined' ? localStorage.getItem('checkout') : null
You can add a polyfill to your app. I.e. somewhere in your index.js
:
if (!window) {
require('localstorage-polyfill');
}