What is the localStorage?
The localStorage is a read-only property of the window interface that allows us to access the Storage for the Document’ origin (aka the browser). It let us save key-value pairs on the user browser. This was introduced on HTML 5 and everything it’s stored as a String, but I will show you how to save JSON objects.
Hold on, localStorage is read-only but let's store data? localStorage is read-only because it's immutable/cannot be overwritten se it's not possible to assign it to another value but we can use it to store data. If this sounds confusing for you don't worry adn keep reading and you will see how to use localStorage to store and retrieve data to the browser easily.
localStorage vs sessionStorage
The difference between localStorage and sessionStorage it’s the expiration date: the localStorage data will persist until:
- We delete the data.
- User clears the browser data.
localStorage data won’t persist if the user is using incognito or private browsing.
sessionStorage data gets expired each time the page it’s reloaded.
Update: regarding of the sessionStorage lifetime as @arandomdev points out:
sessionStorage does survive a page reload, as the browser assigns a session to the tab, and as long as its open, that session will not be cleared. Only when the tab or the browser gets closed that a new session will be assigned and the old sessionStorage will be cleared and a new one will be created.
How to write on localStorage
Data on localStorage is stored as key-value pairs and must always be String. It’s also possible to store and retrieve JSON objects with a little workaround. The function responsible for writing on the localStorage is the setItem
function.
Example:
// Saving user access token
localStorage.setItem('token', 'ksjakdkaugdka2i163mjbdja8y1');
We can check that the informations has been saved by opening the console (f12) and checking the application tab under Local Storage:
Storing objects
In this case I’m saving the personal access token from a user, but what if I have to store an object with the user's details? Let’s try it:
// 1. We define an Object;
const user = {name: 'John', surname: 'Connor', id: 2};
// 2. Try to store the Object:
localStorage.setItem('user', user);
And now check the application tab:
Well it has stored ‘something’ but the content it’s not accessible so it’s useless and if this was an API response we would have lost the response. So how can we store objects in localStorage?
Though localStorage works only with strings so we can make it work transforming the object to a String:
// 1. We define an Object;
const user = {name: 'John', surname: 'Connor', id: 2};
// 2. Transform the Object to String:
const userString = JSON.stringify(user);
// 3. Store the object:
localStorage.setItem('user', userString);
We can check it on the application tab:
The information is there, and more important, accessible.
How to read localStorage data
To read the localStorage data we use the getItem
function and we need to know the key that keeps the data:
Example:
// Reading user access token from localStorage
const token = localStorage.getItem('token');
console.log(token);
Reading objects
Now let’s retrieve the object we stored earlier using the same getItem
function.
const user = localStorage.getItem("user");
console.log(`Welcome ${user.name} ${user.surname}`);
We read the localStorage and try to console log a greeting message using the object’s name and surname properties on console and this is what we get:
The console is returning undefined for the name and surname. Why? because what we stored is not an object it is a String. To read objects from localStorage we need to transform it from String to Object. Let’s try again:
// 1. Reading the object as string
let user = localStorage.getItem("user");
// 2. Parsing the string to Object
user = JSON.parse(user)
// 3. Now we can access the object properties.
console.log(`Welcome ${user.name} ${user.surname}`);
How to find all localStorage keys
We can get an array with all the keys using Object.keys
:
const keys = Object.keys(localStorage);
console.log(keys);
How to remove data
To remove data from localStorage we have 2 options:
Delete one item
We can use the function removeItem
:
Example:
localStorage.removeItem("token");
We can see that the token is no longer on the localStorage:
Delete all items
We can use the function clear
to delete all existing items:
Example:
localStorage.clear();
Drawbacks of localStorage
As I showed localStorage it’s very easy to use and that can lead us to misuses:
- Don't store too much data on it as it has just 5MB per domain.
- All data is easily accessible for the user and any script running on the page and that makes it insecure. So don’t store sensitive information.
- Don’t be tempted to use it as a substitute for a database.
Top comments (10)
"sessionStorage data gets expired each time the page it’s reloaded."
Actually, sessionStorage does survive a page reload, as the browser assigns a session to the tab, and as long as its open, that session will not be cleared. Only when the tab or the browser gets closed that a new session will be assigned and the old sessionStorage will be cleared and a new one will be created.
developer.mozilla.org/en-US/docs/W...
Nice detail, just updated the post to include this. Thanks for your contribution.
Really nice article. Thank you.
Recently I build a small package to monitor the local/session storage usage. If someone's interested, check it out on npmjs.com/package/@dafcoe/storage-....
Don't mix
read-only
with Immutable. Aread-only
storage implies some data has been put in there and is definitely locked, as is the case for ROM where data is burnt inside it.LocalStorage is not
read-only
. The docs says it's aread-only
property of thewindow
object, which means you cannot change the object it points to.Indeed, it is Immutable, but that's not a decision choice, that's rather per se. Strings are immutable, and the value stored are strings.
Maravilhosa explicação, nota máxima.
Porém como exibir no dom os objetos?.
Estou construindo um appweb e estoueio confuso, mas a sua explicação me tirou do limbo do stackoverflow
<>
In english:
Wonderful explanation, top marks. But how to display objects in the gift?. I'm building an appweb and I'm confused, but your explanation got me out of stackoverflow limbo
If I don't get you wrong you want to store and retrieve objects from localStorage? If it's that you then you have to transform the object to string to store it and when retrieving transform the string to object again. It's all explained on this post.
thanks for shareing
Love it
Good article ;)
excellent...thank you so much