Blog |

How to Handle the “localStorage is not defined” Error in JavaScript

How to Handle the “localStorage is not defined” Error in JavaScript
Table of Contents

The localStorage is not defined error generally occurs when you try to access the localStorage object in JavaScript, but the browser environment where your code is running does not support it.

Using the localStorage web storage API, web applications can store key-value pairs locally in a web browser, allowing you to persistently retain data on the client-side even if the user shuts their browser or navigates away from the website.

What causes the “localStorage is not defined” to occur

The localStorage is not defined error can occur for several reasons, such as:

  1. Unsupported Browsers: Some older browser configurations might not support localStorage. So it’s a good option to either check the compatibility before using the browser or move to the latest version of the browser.
  2. Using ‘localStorage’ in Node.js: Since Node.js is a server-side JavaScript environment, it doesn’t have access to the browser's localStorage API. Therefore, using localStorage in Node.js might throw an error. For example:
    try {
      localStorage.setItem('key', 'value');
    } catch (error) {
      console.error(error.message); //raises the error
    }
    

    Output:

    PS D: \BackEnd> node index.js
    localStorage is not defined
    
  3. Using ‘localStorage’ in React.js: Native apps do not have access to the browser's localStorage API, so you will get an error.
  4. Using ‘localStorage’ in Next.js: When using Next.js during server-side rendering, you do not have access to localStorage.
  5. When using a pre-built library or framework: If a library or framework that uses localStorage is executed in an environment where it is not supported, it might raise an error.

How to handle the “localStorage is not defined” error

To handle and resolve the error you can follow the below steps:

  1. Verify the Environment: Verify that you are running JavaScript code in a web browser environment. Since localStorage is specific to web browsers, it will not function in server-side JavaScript.
  2. Browser Compatibility: Check to see if localStorage is supported by the browser you're using. It is supported by almost all current browsers, but if you need to support older versions, you might want to think about using sessionStorage or cookies as alternatives.
  3. Using a Fallback Mechanism: You can utilize feature detection and offer a fallback mechanism to handle environments where localStorage might not be accessible. For instance:
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem('key', 'value');
    } else if (typeof sessionStorage !== 'undefined') {
      // Fallback to sessionStorage if localStorage is not supported
      sessionStorage.setItem('key', 'value');
    } else {
      // If neither localStorage nor sessionStorage is supported
      console.log('Web Storage is not supported in this environment.');
    }
    

Summary

The localStorage is not defined error in JavaScript occurs when you try to use the localStorage object in an unsupported environment, such as Node.js, Next.js, React.js, or older browsers. The error can be resolved by making sure you are using localStorage in a web browser environment that supports it. If necessary, you can implement feature detection and provide fallback mechanisms to handle situations where localStorage is not available. By following these steps, you can ensure your web applications work smoothly across various environments and browsers.

Track, analyze and manage errors with Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Try it today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape