The HTML web storage API provides a way to store data locally within a user's browser. You can use it to securely store a large amount of data locally without impacting website performance.

Unlike cookies, web storage has a significantly higher storage limit (5MB vs 4KB) and the data stored is never sent to the server with every request. Therefore, the server can not manipulate the web storage data via HTTP cookies.

Also, the storage is bound to the origin (per domain, protocol, and port). All web pages, from one origin (with the same protocol, domain, and port), can store and access the same data. Even if you change the protocol from http to https, you can not access the data stored using the http protocol.

Web Storage Objects

HTML web storage provides two objects for saving data as key-value pairs in the browser:

  • localStorage — stores data with no expiration date that persists even after the browser window is closed. You have to explicitly remove data either programmatically or by clearing the browser's data. The data is shared among all the sessions of the same origin.
  • sessionStorage — stores data for the duration of the page session that gets cleared automatically when the browser tab is closed. If you open multiple tabs of the same website, they will have different sessions and can not access data of each other.

Since localStorage persists data with no expiration date, it is useful for storing information such as shopping cart items, user preferences (currency, dark or light color scheme), products bookmarked, or even remembering the user is logged into the website.

Methods & Properties

Both localStorage and sessionStorage objects provide the same methods and properties because they return the same Storage object.

The Storage object has just one property, length, that returns the number of items stored in it.

Here is a list of methods that you can call to manipulate web storage data:

Method Description
setItem(key, value) Add a new key-value pair to the storage
getItem(key) Retrieve a value by its key
removeItem(key) Remove an item by its key
clear() Delete all key-value pairs
key(n) Retrieve the name of the nth key in the storage

Web Storage Examples

Let us play with localStorage to get an idea of how web storage works.

Storing data

The following example uses setItem() to add new key-value pairs to localStorage:

localStorage.setItem('id', 'ATS-456');
localStorage.setItem('email', 'john.doe@example.com');

Note that both key and value passed to setItem() must be strings. If you pass any value that is not a string, like an object or a number, the setItem() method will automatically convert it a string:

localStorage.setItem('visitors', 34); // stored as '34'
localStorage.setItem('user', { name: 'Alex' }); // stored as '[oject Object]'

For objects, you need to use the JSON.stringify() method to convert it to a string before storing into web storage:

const str = JSON.stringify({name: 'Alex'});
localStorage.setItem('user', str);

Retrieving data

To retrieve the stored data in localStorage by key, use the getItem() method:

localStorage.getItem('id');     // ATS-456
localStorage.getItem('email');  // john.doe@example.com

Alternatively, you could also use the dot (.) donation to access keys from localStorage like objects:

localStorage.visitors;  // 45

If the key doesn't exist, a null value is returned by getItem():

localStorage.getItem('name'); // null

Removing data

To delete a key-value pair from localStorage, just pass the name of the key to the removeItem() method:

localStorage.removeItem('id');

Alternatively, you could also use the delete operator to delete a key like an object:

delete localStorage.email;

To remove all key-value pairs, use the clear() method instead:

localStorage.clear();

Iterating over keys

To iterate over all keys stored in localStorage, we can use the for...of loop:

const keys = Object.keys(localStorage);
for (let key of keys) {
    console.log(`${key}: ${localStorage.getItem(key)}`);
}

The Object.keys() method returns all own properties of the localStorage object, ignoring the prototype.

Summary

HTML web storage API provides a mechanism to store data locally within the user's browser. Before web storage, cookies were the only option available for storing application data.

Unlike cookies, web storage is more secure and capable of storing a larger amount of data (5MB+, depending on the browser) without affecting the application performance.

Web storage is bound to the origin, which means that pages from the same origin can only access their own data.

Web storage provides two objects, localStorage and sessionStorage, to save data as key-value pairs in the browser.

The data stored in localStorage is permanent and shared between all tabs and windows with the same origin. It persists even after the browser is closed or the computer is restarted.

The sessionStorage object stores data temporarily until the session is active. The data is only accessible within the same tab and can not be accessed from other tabs. It gets cleared automatically once the browser tab is closed.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.