WittCode💻

JavaScript LocalStorage

By

Learn everything about JavaScript's local storage including when to use it, how to use it, and what to store in it.

Table of Contents 📖

What is Local Storage?

Local storage is a property of the window object (a global object that has properties pertaining to the current DOM document).

Image

Local storage was introduced as part of the Web Storage API in HTML 5. The Web Storage API allows browsers to store key/value pairs. It consists of two mechanisms: session storage and local storage. In this article, we will be focusing on the latter, local storage. Local storage allows the web browser to store data with no expiration date. In other words, local storage data doesn't get erased, even after the browser is closed.

Local Storage uses the Storage Interface

Specifically, local storage is part of the JavaScript Storage interface. The JavaScript Storage interface allows us to retrieve, set, and remove data for a specific domain and storage type (local or session).

Image

Storing and Retrieving Data with Local Storage

To store data with local storage we use the method setItem(), which is part of the Storage interface, and pass it a key and value.

localStorage.setItem('myKey', 'myValue');

To retrieve this value, we use the method getItem() and pass it the key provided to setItem().

const storedLocally = localStorage.getItem('myKey');
console.log(storedLocally)  // myValue

The key of local storage data can be accessed by using the key() method and providing it an index. Similar to arrays, the first index is 0.

localStorage.setItem('My Key', 'My Value');
console.log(localStorage.key(0));   // My Key

It should be noted that the order of these keys is user-agent defined so key() is not a really reliable method. Also, if the index does not exist, null is returned.

Removing Data from Local Storage

undefined

Remember, data stored with local storage is not deleted unless explicitly cleared. The Web Storage API provides two methods for removing locally stored data. The first method is removeItem() which accepts the key of the item to remove.

localStorage.setItem('myFavYTChannel', 'WittCode');
console.log(localStorage.getItem('myFavYTChannel'));    // WittCode
localStorage.removeItem('myFavYTChannel');
console.log(localStorage.getItem('myFavYTChannel')); // null

The other method to remove data is clear() which removes all data in local storage.

localStorage.setItem('myFavYTChannel', 'WittCode');
localStorage.setItem('cheese', 'tasty');
localStorage.setItem('milk', 'good');
localStorage.clear();
console.log(localStorage);  // Should be empty.

What to Store in Local Storage?

Only insensitive data should be stored in local storage as it is stored on the client/browser. As such, anyone with access to the user's browser could look up the local storage data. Some examples of what not to store in local storage are passwords, usernames, and other sensitive user related information. On the other hand, something like color preference for the webpage could be stored in local storage.

Another good use for local storage is HTTP response caching. For example, instead of pulling data from the server with every request, we could store it on the client's local storage and just access it from there.

What are some Local Storage Limitations?

Local storage can only be written to and accessed synchronously meaning it will block the main thread, slowing down program execution. Local storage is also limited to about 5MB of data depending on the browser (some browsers can't even store as much as 5MB). Finally, the keys and values in local storage can only be strings. Non-string data is automatically converted to string data.

localStorage.setItem('myNum', 7);
console.log(typeof localStorage.getItem('myNum'))   // string
localStorage.setItem('myObj', { myObjKey: 'myObjVal' });
console.log(typeof localStorage.getItem('myObj'))   // string

Third-party software can also use local storage. As such, there could be collisions/pollution of the global namespace leading to overwritten data. To combat this it is recommended to prefix data stored in local storage with a unique key.

Detecting if LocalStorage is Available

Another limitation of local storage is that it can be blocked. For example, it can be disabled in browser settings, the client could have turned off JavaScript in their browser, etc. Therefore, it is recommended to have a helper function to check for the availability of local storage to prevent errors or even app crashes. For example, the following script could be used to detect the availability of local storage.

function localStorageAvailable() {
    try {
        localStorage.setItem('testKey', 'testValue');
        localStorage.removeItem('testKey');
        return true;
    } catch (e) {
        return false;
    }
}

if (localStorageAvailable()) {
    console.log('localStorage is available!');
} else {
    console.log('localStorage is not available!');
}

Note that we cannot simply check if localStorage is undefined as the Safari browser offers a functional localStorage object in private mode. So simply checking if localStorage is defined will pass but calls to setItem() will throw an exception.

Viewing Local Storage in the Browser

Local storage information can be viewed in the application tab of the Google chrome dev tools, not just by logging it to the console.

Image

In the application tab we can see local storage for the provided origin. Here, the protocol is http, the domain is localhost, and the port is 1235. There is currently only one local storage key value pair: "fav-wittcode-video" and "local storage video" respectively.

Local Storage is Origin Based

Data stored in local storage is bound to an origin. The term origin is defined by the scheme (protocol), hostname (domain), and port of the URL used to access it. For example, local storage on localhost:1234 will not be the same as local storage on localhost:4567. Similarly, local storage on http://wittcode.com will be different from local storage on https://wittcode.com (http vs https).

Local Storage in Incognito Browser

Local storage set for a document in private/incognito mode is cleared when all tabs are closed for that specific origin.

Summary

But there we have it! Local storage is definitely a cool feature to have in our JavaScript toolkit. If this article was helpful, please consider donating at the top of the page, sharing this article, and subscribing to my YouTube channel WittCode!