DEV Community

Cover image for javascript - Everything you always wanted to know about localStorage (but you were afraid to ask)
Jose C
Jose C

Posted on • Edited on

javascript - Everything you always wanted to know about localStorage (but you were afraid to ask)

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.

Image description

Example:

// Saving user access token
localStorage.setItem('token', 'ksjakdkaugdka2i163mjbdja8y1');
Enter fullscreen mode Exit fullscreen mode

We can check that the informations has been saved by opening the console (f12) and checking the application tab under Local Storage:

Image description

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);
Enter fullscreen mode Exit fullscreen mode

And now check the application tab:
Image description

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);
Enter fullscreen mode Exit fullscreen mode

We can check it on the application tab:
Image description

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:

Image description

Example:

// Reading user access token from localStorage
const token = localStorage.getItem('token');
console.log(token);
Enter fullscreen mode Exit fullscreen mode

Image description

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}`);
Enter fullscreen mode Exit fullscreen mode

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:

Image description

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}`);
Enter fullscreen mode Exit fullscreen mode

Image description

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);
Enter fullscreen mode Exit fullscreen mode

Image description

How to remove data

To remove data from localStorage we have 2 options:

 Delete one item

We can use the function removeItem:

Image description

Example:

localStorage.removeItem("token");
Enter fullscreen mode Exit fullscreen mode

We can see that the token is no longer on the localStorage:

Image description

Delete all items

We can use the function clear to delete all existing items:

Image description

Example:

localStorage.clear();
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
arandomdev profile image
A Random Dev

"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...

Collapse
 
josec profile image
Jose C

Nice detail, just updated the post to include this. Thanks for your contribution.

Collapse
 
dafcoe profile image
Daf Coe

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-....

Collapse
 
thelonearchitect profile image
The Lone Architect

Don't mix read-only with Immutable. A read-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 a read-only property of the window 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.

Collapse
 
shadowruge profile image
izaias • Edited

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

Collapse
 
josec profile image
Jose C

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.

Collapse
 
shibbirahmad profile image
Shibbir Ahmad

thanks for shareing

Collapse
 
rii profile image
Rii

Love it

Collapse
 
arturssmirnovs profile image
Arturs Smirnovs

Good article ;)

Collapse
 
m3hdirostami profile image
m3hdi rostami • Edited

excellent...thank you so much