React - “localStorage is not defined” error showing

后端 未结 3 669
臣服心动
臣服心动 2020-12-31 03:59

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:

相关标签:
3条回答
  • 2020-12-31 04:35

    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');
    }
    
    0 讨论(0)
  • 2020-12-31 04:36

    This oneliner did it for me:

    const checkout = typeof window !== 'undefined' ? localStorage.getItem('checkout') : null
    
    0 讨论(0)
  • 2020-12-31 04:43

    You can add a polyfill to your app. I.e. somewhere in your index.js:

    if (!window) {
        require('localstorage-polyfill');
    }
    
    0 讨论(0)
提交回复
热议问题