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
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 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
localStorage.setItem("num", 90)
localStorage.setItem("user", { name: "nnamdi", age: 21 })
localStorage.getItem("num") // "90"
localStorage.getItem("user") // "[ object Object ]"
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]
.
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"
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"
localStorage datastore persists even when the browser is shut down. The data in localStorage will still be available when the browser is launched next.
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.
Data is never transferred to the server.
Data is shared between all tabs and windows from the same origin.
The much less used API and brother to localStorage, sessionStorage, is an object of Storage that inherits the methods and properties of
These APIs do the same thing, as we have seen in localStorage. Just like localStorage, sessionStorage operates on a specific origin (domain/port/protocol).
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
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).
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
localStorage can be shared between tabs; sessionStorage cannot.
localStorage persists and lives when the browser is closed and reopened; in sessionStorage, everything is cleared once the browser is closed.
localStorage has no expiration date; sessionStorage expires when the page session ends.
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.
Free Resources