JavaScript LocalStorage: A Complete Guide

updated on 26 May 2022

For most web browsers, the web storage API provides a mechanism to store key-value pairs in the browser. It’s generally divided into localStorage and sessionStorage, and the main difference between the two is how long the browser stores the data. With sessionStorage, the data is removed once the session ends or the browser closes. Data in localStorage, though, persists until it is cleared. 

A common real-world example of localStorage is the game Wordle. Once you type in a word and press Enter, the values are stored in localStorage. If you close and reopen the Wordle page on the same device, you’ll get the same words you already tried. The storage is reset at the end of the day.

Wordle-jzkon

The daily answer is also stored in localStorage, so that you can play the game offline after opening the page.

The localStorage feature can prove helpful in a number of use cases. This article will explain more about localStorage and how it works, so that you can use it with your applications. 

Why Do You Need localStorage?

There are a number of useful features in localStorage, including the ability to store user information and to allow you to work offline as needed. 

As part of the web storage API in web browsers, localStorage works similarly to cookies. However, it can store a larger amount of data. The storage available in Google Chrome is 5 MB maximum per domain, while Opera’s localStorage holds 3 MB but can be increased.

Because the internet may not be consistently accessible everywhere, localStorage enables you to take your work offline, just like with Wordle.

You can also store the state of your web page, even though HTTP is stateless. Say you only wanted to use the Solarized Dark theme on the Alligator.io site. Using localStorage, you wouldn’t have to change the theme every time you reopen the browser and visit the site. 

Front end web development-ylfsp

Benefits of localStorage 

Using localStorage offers a number of benefits, including the following: 

- More storage: As noted earlier, localStorage can store up to 5 MB of data in most browsers, much more than what cookies can hold. 

Developer-friendly API: The API makes it easy to access and add data in localStorage. On any browser, the localStorage functions are accessible from the Window object. You can add data just by writing window.localStorage.setItem ("Test Data", "Hello from localStorage")

- Persistence: One of the most common reasons for using localStorage is to keep the data persistent. While sessionStorage can also store data in key-value pairs, it’s cleared when the session ends. With localStorage, however, the data is continuous until it is explicitly removed. 

LocalStorage anti-patterns

Anti-pattern: Saving Access Tokens

A widespread use of localStorage is to store access tokens, such as JWT tokens, on the user’s side so the user stays logged in for a specified amount of time. 

This is insecure and should never be done, since it’s accessible using JavaScript on the same domain. This means any JavaScript code running on the page could access the storage, leaving your application vulnerable to cross-site scripting (XSS) attacks.

Applications also frequently use third-party scripts to get analytics or ads, and if even a single script is compromised, you risk being hacked. 

For more information, check this article about safer ways to store auth tokens. 

LocalStorage Use Cases

Following are some common use cases for localStorage.

Saving Partially Submitted Form Data

If a user is filling out a long form, localStorage can be helpful in storing partial data. Even if the internet is disconnected between beginning the form and submitting it, the user won’t lose their inputs and can continue from where they left off. 

Caching

According to a 2022 analysis by Portent, customer conversion rate can increase by 2.5 times when your page loads in one vs. five seconds. Building a slow website is not an option anymore. But when an end user asks for specific data and the request has to travel across the wire with associated latency, caching can be a life-saver. The localStorage can be used to cache a website or to store static data to show the client information even when the page is offline, then fetch necessary data when the internet reconnects.

Syncing Data Between Tabs

Using localStorage, a user can open a timer website on a browser tab, start the timer, then open another tab of the same website and sync the timer between both tabs. You can also sync music or your video player between tabs.

Pre-populating Data

You can use localStorage to store a pre-populated version of your application. When a user visits your application, they immediately see something on the screen, then your application can make calls to the backend to fetch new information. E-commerce sites often use localStorage to store items the user has viewed and other user-specific data.

Performing Operations on localStorage

You have a few methods to choose from when performing operations on localStorage. They are:

- setItem()

- getItem()

- removeItem()

- clear()

- key()

Following are more details on each one. 

Storing Values with setItem()

The setItem method is used to store values to localStorage. This method takes in two parameters: a key and a value. The key is used to fetch the data later.

Here’s a simple example of using the setItem method to store data:

window.localStorage.setItem("Data", "Hello from localStorage")

If you run this code on a browser console, it will store a key with the name Data and a value of Hello from localStorage on localStorage.

gif-kwkuj

After running the code, if you open the Applications tab and click localStorage, you’ll be able to see the Data key.

Note that you can only store strings in localStorage. (On Firefox and Chrome, the localStorage data is stored inside a Sqlite database.) If you want to keep arrays or objects, a straightforward way is to convert the data to JSON using the JSON.stringify method.

Accessing Items with getItem()

The localStorage API uses the getItem method to retrieve data. The method takes a single argument that is the key to the data. If the data is not found, the method returns null.

The syntax of the code is shown below:

window.localStorage.getItem("Data"); // Hello from localStorage
window.localStorage.getItem("data"); // null
gif2-g3oz8

Removing Specific Item with removeItem()

As the name suggests, the removeItem() method removes a specific key-value pair from localStorage. The syntax of the data is similar to getItem. It also takes a single parameter, the item’s key, and returns undefined if the item is not available.

window.localStorage.removeItem("Data"); 

You can check your Applications tab of the browser dev tools to confirm that the key is removed.

Deleting All Items With clear()

If you want to clear localStorage of a particular domain, use the clear method. It doesn’t take any parameters and removes all localStorage items for the domain.

window.localStorage.clear();

Retrieving Key Names with key()

The key method comes in handy when you want to loop through the keys of localStorage. It takes a parameter of a number. The number can be an index position of the localStorage item.

Here’s an example:

window.localStorage.setItem('Test', 'test'); // Adds New Item
window.localStorage.key(0); // Test

The returned value can be different if your localStorage for the domain already holds some value.

Listening to Storage Events

To listen to events related to localStorage with DOM, use the storage event. Putting it inside a window.addEventListener can help you perform DOM operations when invoking a storage event.

Below is a simple example of listening to storage events:

window.addEventListener("storage", myFunction);
function myFunction(event) {
  document.getElementById("app").innerHTML = "Change Made";
}
function changeValue() {
  const newWindow = window.open("", "myWindow");
  newWindow.localStorage.setItem("mytime", Date.now());
  newWindow.close();
}

Whenever a change is made to localStorage, the code sets an inner HTML to the div with the ID app to Change Made. In this case, a new item is added to localStorage for the new window, and after writing the value to localStorage, the window is closed.

Here’s the HTML for the above code:

<h1 id="app"></h1>
<button onclick="changeValue()">Change a Storage Item</button>

You can also check out the CodePen link for the above example.

LocalStorage vs. SessionStorage 

LocalStorage and sessionStorage do have some similarities. For example:

- Both storage types are offered by the web storage API

- Both can only store string-type values

- The data limit is about 5 MB in most cases

- Both storage types can only store values in key-value pairs 

However, there are several differences between the two. One is persistence: data stored in localStorage persists over sessions. Opening a new tab, visiting a new domain, or closing the browser will not clear localStorage. On the other hand, sessionStorage is cleared whenever a session ends. Opening a new tab or visiting a new domain will clear the session for a specific domain.

Another difference is that, in the case of a few browsers, localStorage doesn’t work in incognito mode but sessionStorage does. In these cases, it’s a good idea to write a wrapper for your localStorage code in order to use sessionStorage.

LocalStorage vs. IndexedDB

IndexedDB is an API for storing a large amount of structured data, including files, on the client side. The data stored using IndexedDB is also persistent and is stored until it’s explicitly cleared. IndexedDB also offers a built-in mechanism for schema versioning.

IndexedDB offers several benefits over localStorage. For instance, IndexedDB doesn’t block the DOM when used with a worker, unlike localStorage. However, localStorage is slightly faster than IndexedDB. The API of localStorage is also much easier to get started with, making it the more popular choice. 

The primary reason for introducing IndexedDB was to make a better version of localStorage. So, why not use IndexedDB in all cases? If you want to store structured data on the client side, IndexedDB is the better choice, especially since localStorage isn’t built to store sensitive information. But if you’re storing a simple, small amount of key-value pair data, use localStorage. 

Conclusion

The localStorage feature can offer benefits to your applications, including open-ended storage to persist data for as long as you need it and the ability to make your applications work offline. This form of data storage won’t be the best choice in every use case, and you might need to consider IndexedDB instead in some instances. 

Meticulous

Meticulous is a tool to create frontend tests without writing code. Use our CLI to record a user session and test a pull request or code change by replaying that user session on the old code and new code. Meticulous captures a screenshot at the end of each replay, and diffs the two to create a simple test. Meticulous records network calls at record-time and automatically mocks out all network calls at replay-time, meaning you don’t need a backend environment to replay against. You can also switch this network mocking off if you wish to hit a backend environment. 


You can integrate Meticulous tests into any CI system, or use our example on integrating Meticulous with GitHub. Read more at our docs at docs.meticulous.ai

Authored by Subha Chanda

Read more