How to use Web Storage APIs

A comprehensive guide to localStorage and sessionStorage APIs

These days, localStorage is usually preferred over cookies because it offers robust and clean APIs for data storage and retrieval. Cookies, on the other hand, are kind of tricky to use and understand.

localStorage and sessionStorage are the only Web Storage APIsstore key/value pairs, but definitely not the only ones used as a means to store data in our browser. The others would be Cache Storage, Cookies, and IndexedDB. To inspect them, open DevTools and click on the Storage tab.

There’s nothing better than getting a hands-on experience of things, so, before we start with written explanations, here’s a demo app I’ve made: Web Storage APIs.

Feel free to check out the source code here.

localStorage

localStorage is a Storage object. Type localStorage in your console, hit enter, and a Storage will be printed.

Console

>> localStorage
> Storage { length: 0 }
>>

Expand the Storage object:

We can see that it inherits from the StoragePrototype that has the clear, getItem, removeItem, key, and setItem methods, as well as the property length.

These are the methods localStorage uses to store and retrieve data from its store. localStorage stores data in key/value pairs, just like in Java with plain old object literals.

  • key: serves as an ID to the actual value it stores or holds.

  • value: the value that is stored and identified with key.

  • clear: clears the localStorage datastore.

  • getItem(key): returns the value from the key/value pair based on the key that is sent.

  • key(index): used to return the key name of a key/value pair from an index.

  • removeItem(key): removes a key/value pair from the data store based on the key that is sent.

  • setItem(key, value): creates and sets a key/value pair in the localStorage datastore.

  • length: a read-only property that returns the number of data stored in the localStorage.

localStorage is available in the window object, so it can be called with or without appending the window prefix:

window.localStorage
// OR
localStorage

Points to note on localStorage

  1. The keys and values are always strings. Note that, as with objects, integer keys will automatically be converted to strings.
    localStorage.setItem("num", 90)
    localStorage.setItem("user", { name: "nnamdi", age: 21 })

    localStorage.getItem("num") // "90"
    localStorage.getItem("user") // "[ object Object ]"
  1. If we need to save an Object in localStorage, we need to stringify it; that is, use JSON.stringify API to convert the JavaScript value to a JavaScript Object Notation JSON string.
    const user = {
        name: "nnamdi",
        age: 27,
        occupation: "doesn't know what he is doing"
    }

    localStorage.setItem("user", JSON.stringify(user))

JSON.stringify will convert the user Object to the JSON string { name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" }.

So, when we retrieve the user value, we get this:

localStorage.getItem("user") 
// "{ name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" }"

If we didn’t use JSON.stringify, the user Object would be converted to the Object string [object Object].

  1. Now, we cannot use the JSON string like that or access the properties because it is a string. To access the properties, we need to convert the JSON string to a JavaScript value using the JSON.parse API.
localStorage.getItem("user") // "{ name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" }"

const userLocal = JSON.parse(localStorage.getItem("user")) // { name: "nnamdi", age: 27, occupation: "doesn't know what he is doing" }

    userLocal.name // "nnamdi"
  1. localStorage operates on a document’s origin. We only have to be on the same origin (domain/port/protocol); the URL path can be different.

    For example, the data stored in localStorage in a https://doc.origin.com domain will not be the same as the data stored in localStorage on https://app.inapp.com.

https://doc.origin.com
    localStorage.setItem("name", "nnamdi")

https://app.inapp.com
    localStorage.setItem("name", "chidume") 

So, if we try to get the value of the name key on https://doc.origin.com:

localStorage.getItem("name") // "nnamdi"

And if we try to get the value of the name key on https://app.inapp.com:

localStorage.getItem("name") // "chidume"
  1. localStorage datastore persists even when the browser is shut down. The data in localStorage will still be available when the browser is launched next.

  2. Data stored in localStorage never expires, meaning it has no limit data, life limit, or expiration date. It lives in the browser forever until it is cleared by the user.

  3. Data is never transferred to the server.

  4. Data is shared between all tabs and windows from the same origin.

sessionStorage

The much less used API and brother to localStorage, sessionStorage, is an object of Storage that inherits the methods and properties of StoragePrototypethe Storage parent class just like localStorage does.

These APIs do the same thing, as we have seen in localStorage. Just like localStorage, sessionStorage operates on a specific origin (domain/port/protocol).

Example code

mySessionStorage = window.sessionStorage || sessionStorage

sessionStorage.setItem("userId", "23ert5Y")
sessionStorage.setItem("name", "nnamdi")

sessionStorage.getItem("userId") // "23ert5Y"
sessionStorage.getItem("name") // "nnamdi"

sessionStorage.length // 2
sessionStorage.key(0) // "23ert5Y"
sessionStorage.key(1) // "nnamdi"

sessionStorage.removeItem("name")
sessionStorage.getItem("name") // undefined

sessionStorage.clear()
sessionStorage.getItem("userId") // undefined
sessionStorage.getItem("name") // undefined

sessionStorage.clear()
sessionStorage.getItem("userId") // undefined
sessionStorage.getItem("name") // undefined

Important notes on sessionStorage

  1. Data stored in sessionStorage has an expiration time. This means that sessionStorage data is cleared when the page session ends.

    A page session is held during the lifetime of a tab. The page session ends when:

    • the tab is closed.

    • the browser/browser window is closed.

    • a new tab is opened; this creates another sessionStorage object even if the tab is of the same origin (domain/port/protocol).

    The page session is maintained when:

    • the tab is refreshed.

    • with iframes.

    We create a sessionStorage at https://doc.origin.com:

sessionStorage.setItem("name", "nnamdi")

If we open another tab at https://doc.origin.com:

sessionStorage.getItem("nnamdi") // undefined

The sessionStorage for the second tab is different from the sessionStorage for the first tab, despite being of the same origin, https://doc.origin.com, unlike localStorage.

It is safe to say that localStorage is shared between tabs of the same origin while sessionStorage is not shared.

The storage limit is larger than a cookie (at most, 5MB).

Web Storage event

This is an event registered on the Web Storage medium localStorage and sessionStorage. The Web Storage event is fired when the data in localStorage and sessionStorage is added, cleared, or deleted.

To register an event:

    window.onstorage = function(event) {}
    
    window.onstorage = function({
        key,
        oldValue,
        newValue,
        url,
        storageArea
    }) {}

The event param has the following properties.

  • key: the key that is changed (null if .clear() is called).

  • oldValue: the old value (null if the key is newly added).

  • newValue: the new value (null if the key is removed).

  • url: the URL of the document where the update happens.

  • storageArea: either a localStorage or sessionStorage object where the update happens.

Source: https://javascript.info

Conclusion

Differences

  1. localStorage can be shared between tabs; sessionStorage cannot.

  2. localStorage persists and lives when the browser is closed and reopened; in sessionStorage, everything is cleared once the browser is closed.

  3. localStorage has no expiration date; sessionStorage expires when the page session ends.

Similarities

  • Holds data on the same origin (domain/port/protocol); the URL path can be different.

  • The data is stored in String format. Objects, numbers, etc., will be converted to a string.

Attributions:
  1. undefined by undefined