Local Storage: What, When, and How?

Cory Rosser
4 min readMay 28, 2020

--

What?

localStorage is a part of the HTML5 Web Storage API. It allows you, the developer, the ability to store information within the browser and gives you a way to easily retrieve and use the stored data. Data is stored in the form of "key"

Information stored in localStorage is client-side, and unlike cookies, it is not sent back to the server and never expires.

It’s easy to read about Local Storage and not quite understand when or why to use it and what differentiates it from other Web Storage solutions so let’s compare Local Storage to Cookies and Session Storage.

Local Storage vs. Cookies vs. Session Storage

From this chart, we can easily see the differences between these three Web Storage options. The first difference is in the amount of disk space allocated to each one. Cookies and SessionStorage both are limited to 4KB and 5MB respectively, while Local Storage ranges from 5–10MB and even down to 2MB in the case of Android Browser v4.3.

  1. Google Chrome: 10MB
  2. Android: 2MB
  3. Firefox: 10MB
  4. Safari: 5MB

Second, while Session Storage and Cookies both expire depending on we-page settings or window/tab closure, Local Storage never expires unless explicitly deleted via JS or the user manually deletes it. Also, Local Storage and Session Storage are both only read by the client. This is important because it allows sites to store specific information about a particular user without the browser having to send any information to the server and await a response.

When and How to use Local Storage?

Local Storage provides us with 5 easy methods to use in order to read, access, and manipulate it.

  1. localStorage.setItem("key", "value") : add a key : value entry into Local Storage.
  2. localStorage.getItem("key") : retrieve the value of a key by passing the key into the method as an argument
  3. localStorage.removeItem("key") : remove an entry from Local Storage by passing the key as an argument
  4. localStorage.clear() : clears all entries in Local Storage
  5. localStorage.key(n) : given a number, will return the nth key

Local Storage can only store strings as a data type, and attempting to store any other data type will result in the automatic conversion of that object into a string. However, by converting our data into JSON, via methods such as JSON.strigify() to store an entry, and JSON.parse() when getting an entry, we can easily store and access JavaScript objects via Local Storage.

On the client-side, each browser and operating system have a place set aside for the allocation of local storage. For example, Chrome stores LocalStorage in the following directory:

~/Library/Application Support/Google/Chrome/<Profile>/Local Storage/ 

While Firefox stores in the following:

~/Library/Application Support/Firefox/Profiles/<profile folder>/webappsstore.sqlite 

A common implementation of Local Storage is keeping track of a which user is logged in to our app on a particular device. In order to do that, at some point in the login process, after authentication and verification, we want to add a new item to our Local Storage.

let user = {
id: 1,
first_name: "Cory"
}
>> Successful Loginwindow.localStorage.setItem("current_user", JSON.strigify(user))

With that done, we now converted our user object into a string that can be stored within Local Storage. So now in order to retrieve that information in your app, you would do the following:

JSON.parse(window.localStorage.getItem("current_user"))>> user = {id: 1, first_name: "cory"}

Local Storage is simple and effective to use but can be just as easy to misuse as well.

The wise use of LocalStorage

While LocalStorage can be incredibly useful, it’s still vulnerable when used to store sensitive information. Local Storage is at risk to Cross-Site-Scripting attacks and information stored within it could possibly fall into the wrong hands as a consequence. LocalStorage, while very fast at retrieving and storing information, is also synchronous which means any calls to it will execute after the previous call finishes and can cause unexpected issues if you’re attempting to use it in asynchronous functions. Local Storage should also never be mistaken as an alternative to a back-end database as it is limited in storage capacity and can be accessed by anyone with access to your local files.

Local Storage Encryption

The best way to ensure security while using Local Storage is through encryption. Encryption is the process of converting information or data into a code, especially to prevent unauthorized access. The most popular method of encrypting Local Storage is through the secure-web-storage package. The following code is an example usage of this library

var CryptoJS = require("crypto-js");var SECRET_KEY = 'my secret key';var secureStorage = new SecureStorage(localStorage, {hash: function hash(key) {key = CryptoJS.SHA256(key, SECRET_KEY);return key.toString();},encrypt: function encrypt(data) {data = CryptoJS.AES.encrypt(data, SECRET_KEY);data = data.toString();return data;},decrypt: function decrypt(data) {data = CryptoJS.AES.decrypt(data, SECRET_KEY);data = data.toString(CryptoJS.enc.Utf8);return data;}});var data = {secret: 'data'};// there is no need to stringify/parse you objects before and after storing.secureStorage.setItem('data', data);// stores in localStorage like:// key => value// "ad36d572..." => "w1svi6n..."var decryptedData = secureStorage.getItem('data');// returns { secret: 'data' }secureStorage.removeItem('data');// removes the entry 'data'secureStorage.key(id)// returns the hashed version of the key you passed into setItem with the given id.secureStorage.clear();// clears all data in the underlining sessionStorage/localStorage.secureStorage.length;// the number of entries in the underlining sessionStorage/localStorage.

See Local Storage In Action

Popular uses of LocalStorage can be found on any major site by right-clicking on the web page and clicking ‘inspect’, followed by clicking ‘Application’ from the top menu and navigating to ‘Local Storage’. If you do this on a site such as YouTube or Reddit, you’ll see that they store information such as user-preferences in Local Storage. You might find that they are storing things like your settings for dark-mode and light-mode, or your video-volume settings, for example, on YouTube. They store information that isn't sensitive by nature and needs to be accessed very quickly by the client.

--

--

Cory Rosser
Cory Rosser

No responses yet