javascript - Everything you always wanted to know about localStorage (but you were afraid to ask)
Tags: javascript, webdev, programming, html
Published: 2021-11-16 08:12:18

# 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ablfvvkryso7fyragbgs.png)

Example:
```javascript
// 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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/so69j5esmfns9j1zsy65.png)

## 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:

```javascript
// 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:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w34suixosvzlc2rlp3fz.png)

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:

```javascript
// 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:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u96pck0bfzplynwx3fw4.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6b2izmlpapeoit5pm96q.png)

Example:
```javascript
// Reading user access token from localStorage
const token = localStorage.getItem('token');
console.log(token);
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxo1gfcgzeuxfsrp7mkg.png)

## Reading objects
Now let’s retrieve the object we stored earlier using the same `getItem` function. 

```javascript
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:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ux9pu90ic1os14dtbiu8.png)

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:

```javascript
// 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}`);
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3kzv7p652d9f37u277e.png)

# How to find all localStorage keys
We can get an array with all the keys using `Object.keys`:
```javascript
const keys = Object.keys(localStorage);
console.log(keys);
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5rw6d8hzc7qz2zvyuf5j.png)

# How to remove data
To remove data from localStorage we have 2 options:

## Delete one item
We can use the function `removeItem`:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kfcpb11670mr1bayolzm.png)

Example:
```javascript
localStorage.removeItem("token");
```
We can see that the token is no longer on the localStorage:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6gx7hgaya58kojzndtg.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aftuc1y34nojqv79togi.png)

Example:
```javascript
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.