localStorage in JavaScript

Abstract image used to represent localStorage in JavaScript
Image by Maximalfocus.

localStorage can be considered a close relative to cookies, in that it allows you to store data within the user's browser. It was introduced with HTML5 as a more capacious mechanism for storing meaningful amounts of data clientside. Whereas cookies generally cannot exceed around 4KB in size, localStorage can usually use more space on the user's system. The specification does not set a fixed quota: the amount available varies by browser, origin, browsing mode, and storage policy, and a write can fail when storage is unavailable or full.

Unlike cookies, localStorage does not have an itemlevel expiry date and is not transmitted automatically with requests. It normally persists across browser sessions, but users, browsers, privatebrowsing rules, and storage policies can still clear or deny it. It offers a cleaner solution than attempting to use cookies with a decadeplus expiry date as a storage medium for nonsensitive preferences.


Getting, Setting, and Removing

Setting

You can insert data into localStorage extremely easily with the helpfullysemantic setItem method, like so:

localStorage.setItem('currency', 'USD');

setItem takes two parameters, the first being the name of the item (so that you can access it again later), and the second being the actual data that you want to store.

It is worth bearing in mind that you can only store strings in localStorage (to be pedantic: the spec says these are of type DOMString). If you attempt to insert a datatype other than string, the browser will convert it. This means that if you are working with more complex data objects, you will need to convert them into a JSON string before storing them.

This is straightforward to handle using JSON.stringify:

const yourData = {
  lorem: 'ipsum',
  foo: 'bar',
};

localStorage.setItem('dataName', JSON.stringify(yourData));

Getting

There are a couple of ways to retrieve items from localStorage. The first, more verbose way, is to use the getItem method, like this:

localStorage.getItem('currency');

The localStorage object also exposes stored keys as properties, so bracket or dot notation can appear to work. Prefer getItem: its missingkey contract is null, whereas missing JavaScript properties produce undefined.

localStorage.currency;
// OR:
localStorage['currency'];

Remember that if you've stored a stringified JSON object as we discussed above, then you will need to use JSON.parse to recover the data:

JSON.parse(localStorage.dataName);
// OR:
JSON.parse(localStorage['dataName']);
// OR:
JSON.parse(localStorage.getItem('dataName'));

Assuming that dataName exists and contains valid JSON, each access form can retrieve the stored string for parsing. Only getItem, however, has the specified null result for a missing key.

Getting a Non‑Existent Item

Often half the battle with JavaScript is safeguarding functions against unexpected or undefined returns. The getItem method in the Web Storage specification requires that a nonexistent key should return null, which means you can very easily check for existence (or not) by comparing it against null:

if(localStorage.getItem('keyName') !== null) {
  // keyName exists
}

Removing Items

If you need to remove an item from Local Storage that was set from your site, you can use the removeItem method with the name of the item, much like when setting:

localStorage.removeItem('currency');

You can also remove all items set by your site from Local Storage by using clear:

localStorage.clear();

localStorage vs. sessionStorage

A question I've been asked a few times in the past is the difference between using localStorage and sessionStorage. The quick answer is that they are virtually identical both in APIs and capabilities. You set an item in sessionStorage using the same setItem method:

sessionStorage.setItem('currency', 'USD');

The important boundary for sessionStorage is the page session in a particular browser tab, with a separate storage area for each origin. It survives reloads and navigation within that tab. Closing the tab normally ends the session, although browser session restoration can restore it. Simply leaving a particular page or finishing a task does not clear its keys.

When working on lazyloading and retaining scroll position for the browser back button on the John Lewis Product Listing Page, I chose sessionStorage for the chunked data. It was useful whilst navigating between the listing and detail pages in the same tab. Clearing that data when the shopping flow ends is a separate application decision: sessionStorage cannot infer when the visitor has finished, so that requirement needs explicit cleanup such as removeItem.

On the flip side, I often use localStorage for nonsensitive preferences that a visitor might expect to persist across visits, rather than only within one tab's page session.

Other simple examples include the order of projects on my personal website homepage because otherwise, it could be confusing for visitors when they hit the back button. Or, even the weather conditions on my About page, because the weather here in Brighton changes frequently, but I don't want to be bothering the BBC service every time you move between pages!

If your website or application needs to store and access data on an ongoing basis then it is likely that localStorage will be preferable over sessionStorage.


A Word on Browser Compatibility

It is fair to say that localStorage and sessionStorage are no longer particularly new APIs, and can be relied upon in a little over 95% of visitors. However, there are some notable exceptions in early releases of Firefox and later versions of Internet Explorer. Depending on what your application traffic looks like (or is expected to look like), you may still want to safeguard against it by checking support before attempting to use it.

In code that may run during server rendering, guard access before checking the window:

// returns 'true' if localStorage is supported
typeof window !== 'undefined' && 'localStorage' in window

Of course, you can do the exact same as above with sessionStorage too. Check the API you intend to use rather than assuming that the availability or policy for one proves the other is usable.

It is worth wrapping storage interactions in a feature check and error handling if your application depends on the data. Access and writes can still throw because of browser policy, privacy mode, or quota limits. If you need to support a high level of legacy browser visitors, then sadly this may not be the solution you need.


Wrapping Up

Both sessionStorage and localStorage are straightforward ways to persist nonsensitive clientside data between page loads. Any script running on the same origin can read or change that data, and encoding or encrypting it with clientside material does not turn browser storage into a trusted security boundary. Do not store sensitive or securityrelated data there; use a trusted backend source of truth instead.


Looking for technical direction?

I support teams that need senior judgement on React, Next.js, headless CMS architecture, performance, migrations, and technical SEO.