Web Storage API: localStorage and sessionStorage

June 11, 2018 0 Comments

Web Storage API: localStorage and sessionStorage

 

 

Web Storage API is used to store data in the browser and was introduced in HTML5. It brought us localStorage and sessionStorage. At the first glance, they seem similar. There are some important differences between them though, which is what we will talk about today. You will learn what their use-cases are and how to incorporate them into your code.

Web Storage API

LocalStorage and sessionStorage are a part of Web Storage API. It provides a way to store key/value pairs in the browser. It won’t disappear after refreshing the page. Both localStorage and sessionStorage are an instance of the Storage object.

If you would like to know more about prototypes, check out my other article: Prototype. The big bro behind ES6 class.

Storage

Since they both localStorage and sessionStorage inherit from the Storage prototype, they share the same set of methods and properties.

One of the basic functionalities of a storage is saving items. To do it, you need a setItem method. The first argument is the key (the name of the item), and the second one is the value. To retrieve it, you use getItem that needs the key to retrieve the value:

After evaluating the code above, open DevTools and go to Application tab. In the Storage section, you can observe that the value was added to the store. An important thing to keep in mind is that it has to be a string: if you want to save an object, you need to stringify it first:

Without using JSON.stringify, the object would have been changed into a string such as  [object Object]. If it seems weird, my other article might prove to be helpful to you: [1] + [2] – [3] === 9!? Looking into assembly code of coercion.

You get them as strings also, so remember to parse them into objects again:

Using setItem with the same key will overwrite the previous value. If you would like to remove it, use removeItem:

sessionStorage.removeItem('user');

To remove all of the stored values, use the clear method:

It is also important that both sessionStorage and localStorage are per origin. It means that they will be shared between pages of the same site, but you will not have access to storages used for other sites.

If you try to create your own storage, it will fail. The only instances of Store are localStorage and sessionStorage:

But how do they differ from each other? Let’s find out!

SessionStorage

An important thing about it is that data stored in sessionStorage gets cleared when the page session ends. Refreshing a page, or going to a different subpage of the same origin will not erase it. Opening a page in a new tab or window will cause a new session to be created with a new storage. For example, go to https://www.reddit.com and open developer tools. Run a piece of code like that:

Then, in the same tab open https://www.reddit.com/r/javascript/ and run:

It is still there! On the other hand, if you open a new tab and try to get that item, there won’t be any trace of it, because it is a new session.

LocalStorage

Its data is saved across browser sessions and has no expiration date. Due to that, it will be shared between tabs and windows of the same origin. You can easily track that with the  onstorage event. Go to https://www.reddit.com/r/javascript/ and in the devtools console type:

Then open a new tab on https://www.reddit.com and type:

In your previous tab, you will see  dogName: null => Fluffyy in the console.

Limitations and use cases

Remember that the same origin does not include subdomains. Storage won’t be shared between https://developer.mozilla.org/ and https://www.mozilla.org/

According to the Wikipedia, the current capacity of the Web Storage on Chrome is 10MB, both for localStorage and sessionStorage combined, but this size might differ between browsers.

A good use case of web storage might be for example to store some configuration for the user, even if he is not logged in, such as a color theme. Another might be to check if he has already been on our site. If not, we might show him some tips on how to use our interface. You might feel tempted to save an authorization token in the localStorage, but wait for a second… Any JavaScript code on your page can access the storage. Beware of the Cross-site Scripting! And not only that. If one of your dependencies ever gets infected (and we have a history of such things happening), it might scan your storage looking for sensitive data. There might be a more suitable option for that: cookies. We will cover them in the next article.

Summary

Web Storage API is a feature that might come in handy, but it is not suitable for every situation. It can only store string data, and JSON serialization takes time. It can store only up to a few MB of data, Operations on storage are synchronous, and can’t be used with web workers. The most important thing about them is the fact, that you shouldn’t store any sensitive data inside. If you remember all that, you should be fine, and they might prove to be useful to you.


Tag cloud