localStorage in JavaScript

Hero image for LocalStorage in JavaScript. Image by Maximalfocus.
Hero image for '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 in a secure and persistent manner. Whereas cookies generally cannot exceed around 4KB in size, localStorage can utilise much more space on the user's system. Although the spec does not define how much space a browser should allow to a domain, it is generally accepted that 2.5MB is the minimum, whereas most browsers allow around 5MB.

Unlike cookies, localStorage does not have an expiry date, and is not transmitted back and forth when the client communicates with a resource belonging to the website. It offers a much cleaner solution than attempting to use cookies with a decadeplus expiry date as a storage medium.


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');

However, as localStorage returns an object, using the getItem method is not entirely necessary. You can access items within localStorage directly via the name using traditional brackets or dot notation:

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 actually exists, any of the three options above will return the same intact JavaScript object.

Getting a Non‑Existent Item

Often half the battle with JavaScript is safeguarding functions against unexpected or undefined returns. The getItem method in the webStorage 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.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 key exception between the two is that localStorage will persist across visits whereas sessionStorage as the name suggests) is only available during a single browser session. Whilst it will survive across navigation within the site, and the page reloads, it is discarded as soon as the session ends (most usually when the browser window is closed).

When working on lazyloading and retaining the scroll position against the browser back button on the John Lewis Product Details Page, it was sessionStorage I settled upon to store chunked data in. This was very shortlived data that was only necessary whilst the user was interacting with the Product Listing or Details Pages so it made sense to clear it again as soon as the user moved on.

On the flip side: I will often use localStorage as a means to store data that a user might expect to persist across visits, things like personal settings or preferences are key examples.

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.

This is as simple as checking to see if it exists in the window:

// returns 'true' if localStorage is supported!!(window && window.localStorage)

Of course, you can do the exact same as above with sessionStorage too, but it is fair to assume that if one is not supported, the other will not be available to you either.

It is worth wrapping your interactions with the storage API with a check if your application will depend on the data. If you are in the unfortunate position of needing 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 a great way for persisting nonsensitive data on the client side and between different page loads and are very straightforward to set up and use. The data stored within these mediums, however, can easily be read or changed from within the client. It should never be used for sensitive or securityrelated data within an application, where a more robust backend source of truth will be required for your application.


Categories:

  1. Front‑End Development
  2. Guides
  3. JavaScript