Javascript local storage - beginner's guide
Tags: javascript, webdev, react, tutorial
Published: 2021-05-12 20:42:46

Before going into any kind of explanation, we need to understand the difference between `server side storage` and `client side storage` when it comes to websites and applications. Server side means that we store our data on a server, using a database, client side consists of JavaScript APIs that allow you to store data on the client (in the browser).

**WHAT IS LOCAL STORAGE?**
In simple terms, the `local storage` can be compared to a data base, except it's found in a browser and not on a server. It's basically a huge Javascript object inside which we are able to store data in the form of `key-value` pairs. Not only we can store data, we can also delete it or retrieve it (a complete list of browsers which have a `localStorage` cant be found [here](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)). The data you store in the `localStorage` never leaves you machine (doesn't get sent back to the server, unlike with `cookies`, which will discuss in a future article), and depending on the browser, you can store up to 5MB of data. 

In technical terms, 
>the localStorage read-only property of the `window` interface allows you to access a `Storage` object for the `Document's` origin; 
the stored data is saved across browser sessions.

**WHY USE IT?**
Local storage lets us cache (store) some application data in the browser, for later usage. Therefore, it is very useful if we want to speed applications up (since the data is stored totally on the client, it does not travel between the client and server on each request or response). This way we can allow an user, for example, to continue a game where they left off or serve them relevant content based on their previous visit of our website.

*I'm mostly using it when I'm building static websites. Since I don’t need any backend language or logic to store data in the browser, my web pages can run independently of any web server.*

There are two types of storages, `local` and `session`, but for now the only difference you should remember is that the `local storage` has no expiration date (meaning that the data will stay in there until we remove it manually), whereas the `session` one gets cleared once we close the browser (session).

I will be using `Chrome` browser for this article, but generally, accessing the localStorage of any browser is pretty similar. We open the console (F12), navigate to the `Application` tab and in the menu on the left we'll see `Local storage` under the `Storage` tab. Something like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7a6mjcf6y7y2dalupgi.PNG)

If we expand the `Local storage` dropdown, we'll get to this view:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e6yuq3uix5qvy1mzk6nx.PNG)

We have two columns, `Key` and `Value`, and usually they're filled with data, which I just removed before taking the screen shot.

The way we can access this `storage` object and populate the two columns is by making use of some specific methods. Remember, `local storage` is `read-only`, meaning we can add, read and delete data from it but we can't modify it (at most, we can overwrite the previous value of a key, by re-adding to the storage, using the same key and the new value we want to store). For access we should use the following syntax:

```javascript
window.localStorage 
//or 
localStorage
```

If we want to add something, we can do it like this:

```javascript
localStorage.setItem("key", "value");
```

To access a value, we write this:

```jvascript
localStorage.getItem("key");
```

And lastly, we can delete one specific value:

```javascript
localStorage.removeItem("key");
```

Or we can clear the whole local storage:

```javascript
localStorage.clear();
```

Now, let's try to actually write some code. I will use my console, for simplicity's sake. Let's add an item:

```javascript
window.localStorage.setItem("city", "Toronto");
```
Now, local storage looks like this: 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5sli70mak2rpyuadqf02.PNG)

One important thing to remember is that the `localStorage` can store only strings. To store objects, we must first convert them to strings using the JSON. stringify() method. And we convert the strings back into objects, after we retrieve them from the localStorage, using the JSON.parse().

Let's add some more values, using different types of data as keys and values:

```javascript
localStorage.setItem(0, "number");
```

```javascript
const person = {name: "Alan", age: 32};
JSON.stringify(person); // returns "{\"name\":\"Alan\",\"age\":32}"
localStorage.setItem("person","{\"name\":\"Alan\",\"age\":32}");
```

Now the local storage will look like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zo19v2tc4b79shq1qpwc.PNG)

We can add as many key-value pairs as we want as long as the data doesn't exceed `5MB`. Now let's retrieve the value of the `person` key, convert it to an object and print it to the console:

```javascript
const result = localStorage.getItem("person");
console.log(result); // returns {"name":"Alan","age":32}
const objectResult = JSON.parse(result);
console.log(objectResult);// returns {name: "Alan", age: 32}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ep78mzwuae493xg5rgy3.PNG)

Finally, let's delete one item only, followed by clearing the whole `localStorage`:

```javascript
localStorage.removeItem("0");
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9j10zau4tl0e4eroe6wm.PNG)

```javascript
localStorage.clear();
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cmio0l7maaovcyyxnwz6.PNG)

**THINGS TO REMEMBER ABOUT THE LOCAL STORAGE**
- it is tab specific, meaning each browser tab we open will have different data in the `localStorage`(this doesn't apply if the tabs have the same origin (share the same domain))
- some browsers, when used in `incognito mode` don't allow for setting data in the `localStorage`
- it is synchronous, meaning each operation will execute one after the other (this might work for small projects, but it will impact the runtime of the more complex ones)
- it can only store data string data (this is fine for small projects, but it can be cumbersome to `serialize` data in complex ones)

**SUPER IMPORTANT THING TO REMEMBER**
Local storage should under no circumstances be used to store sensitive information (e.g. passwords or personal details), since the data inside it can be accessed from anywhere on the page (it has no real protection and it's susceptible to cross-site scripting).

*Image source: ThisIsEngineering/ @thisisengineering on Pexels*