Store Data in the Browser with JavaScript

How to store data with localStorage and sessionStorage. The benefits of each, and when you should use one instead of the other

Photo by Raymond Rasmusson on Unsplash

localStorage and sessionStorage are web storage objects that you can use to save information on the browser. Data added to sessionStorage can survive trough page reloads and localStorage keeps your data even with the browser closing and reopening.

These storages offer some interesting features. They differ from cookies in not being sent to server with each request, which allows it to be bigger (most browsers have at least 2 Mb). Everything is done trough JavaScript, there is no meddling with data by the server trough HTTP headers. Every storage is defined by the triplet domain, protocol, port, so data from one application can’t be accessed by another.

These storage objects offer the same methods and properties:

  • setItem(key, value) store key/value pair.
  • getItem(key) gets the value by key.
  • removeItem(key) remove the key and value.
  • clear() delete everything from the storage.
  • key(index) get the key from a given position.
  • length the count of stored items.

To understand this a little better, let’s go over some examples.

localStorage

Data on localStorage is shared between all browser windows from the same origin (remember the triplet: domain, protocol, port). Also, it is kept locally on disk, hence the name, so it will survive even trough an OS restart.

As long as you keep the triplet consistent, you can store data with localStorage.setItem(‘test’, 1); on one window and read it with localStorage.getItem(‘test’); on another. Note that you can change the URL, only the domain has to be the same.

Another interesting fact is that the same information will be available to all windows of the same triplet. Changes on one will be reflected on the other.

Accessing Data on localStorage

You can use the methods listed above to retrieve the data or use an object like notation. Object notation is clearer, but it opens the door to some bugs. Here you will see what I mean.

https://medium.com/media/8945437ca849595c68b4be25392b7b08/href

On line 12 we try to add a value of 5 to the key ‘length’, but using object notation JavaScript thinks we are referring to the property length and gives us an error.

On line 15 we do the same thing, but since we are using localStorage’s setItem() method, JavaScript knows we want to set the value for the ‘length’ key.

Listing All Keys

You have more than one way to loop over all keys on localStorage, but it is not an iterable, so they are not straight forward. You can do it like a regular array, using for … in , and using the keys property.

To iterate as an array use something like this:

https://medium.com/media/462dde45625d73620b484ae4dc0abeba/href

If you prefer using a for … in keep in mind that it will also get some of the built in stuff that localStorage has, like methods and properties. To work around that we must add a check to remove built ins.

https://medium.com/media/2e17471fc43e968baac9c58ca86ee7df/href

The easier way is to use the keys and get all keys from the object. Because keys is at the object level it won’t list the methods and attributes from the prototype (I have another article on Medium with an explanation of prototypes in JavaScript).

https://medium.com/media/1de839d4febac856a11aac69cece7c65/href

localStorage Only Deals With Strings

That is right, both key and values are always strings. Even if you try to set a numeric value, like we did above, it will be cast to string.

More complex types can be stored with a workaround.

https://medium.com/media/3caa9521bc7450cfb309c8ee969d3543/href

sessionStorage

sessionStorage has the same methods and properties as localStorage, but it only stores data while the session is open. The information will persist between refreshes, but not if you close the browser. For that reason sessionStorage is used less often than localStorage.

Storage Event

Whenever an update happens to either sessionStorage and localStorage, an event is triggered on all windows that have access to the storage, except the one that caused it.

The following are properties of this event:

  • key the key that was changed (null if .clear() is called).
  • oldValue the old value (null if the key is newly added).
  • newValue the new value (null if the key is removed).
  • url the url of the document where the update happened.
  • storageArea either localStorage or sessionStorage object where the update happened.

https://medium.com/media/4a3e58fb904df737bab744fedcc7b78e/href

Conclusion

Both methods of storing data on the browser have their uses. sessionStorage is more limited, only storing data for the current window. localStorage has more uses, because the data is kept even when the browser closes.

If you liked this article, please share with your friends and consider following me on Medium.

Unlock 10x development with independent components

Building monolithic apps means all your code is internal and is not useful anywhere else. It just serves this one project. And as you scale to more code and people, development becomes slow and painful as everyone works in one codebase and on the same version.

But what if you build independent components first, and then use them to build any number of projects? You could accelerate and scale modern development 10x.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing modular applications. Many teams start by building their Design Systems or Micro Frontends, through independent components. Give it a try →

An independent product component: watch the auto-generated dependency graph


Store Data in the Browser with JavaScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Pedro Henrique

How to store data with localStorage and sessionStorage. The benefits of each, and when you should use one instead of the other

Photo by Raymond Rasmusson on Unsplash

localStorage and sessionStorage are web storage objects that you can use to save information on the browser. Data added to sessionStorage can survive trough page reloads and localStorage keeps your data even with the browser closing and reopening.

These storages offer some interesting features. They differ from cookies in not being sent to server with each request, which allows it to be bigger (most browsers have at least 2 Mb). Everything is done trough JavaScript, there is no meddling with data by the server trough HTTP headers. Every storage is defined by the triplet domain, protocol, port, so data from one application can't be accessed by another.

These storage objects offer the same methods and properties:

  • setItem(key, value) store key/value pair.
  • getItem(key) gets the value by key.
  • removeItem(key) remove the key and value.
  • clear() delete everything from the storage.
  • key(index) get the key from a given position.
  • length the count of stored items.

To understand this a little better, let's go over some examples.

localStorage

Data on localStorage is shared between all browser windows from the same origin (remember the triplet: domain, protocol, port). Also, it is kept locally on disk, hence the name, so it will survive even trough an OS restart.

As long as you keep the triplet consistent, you can store data with localStorage.setItem('test', 1); on one window and read it with localStorage.getItem('test'); on another. Note that you can change the URL, only the domain has to be the same.

Another interesting fact is that the same information will be available to all windows of the same triplet. Changes on one will be reflected on the other.

Accessing Data on localStorage

You can use the methods listed above to retrieve the data or use an object like notation. Object notation is clearer, but it opens the door to some bugs. Here you will see what I mean.

On line 12 we try to add a value of 5 to the key 'length', but using object notation JavaScript thinks we are referring to the property length and gives us an error.

On line 15 we do the same thing, but since we are using localStorage's setItem() method, JavaScript knows we want to set the value for the 'length' key.

Listing All Keys

You have more than one way to loop over all keys on localStorage, but it is not an iterable, so they are not straight forward. You can do it like a regular array, using for ... in , and using the keys property.

To iterate as an array use something like this:

If you prefer using a for ... in keep in mind that it will also get some of the built in stuff that localStorage has, like methods and properties. To work around that we must add a check to remove built ins.

The easier way is to use the keys and get all keys from the object. Because keys is at the object level it won't list the methods and attributes from the prototype (I have another article on Medium with an explanation of prototypes in JavaScript).

localStorage Only Deals With Strings

That is right, both key and values are always strings. Even if you try to set a numeric value, like we did above, it will be cast to string.

More complex types can be stored with a workaround.

sessionStorage

sessionStorage has the same methods and properties as localStorage, but it only stores data while the session is open. The information will persist between refreshes, but not if you close the browser. For that reason sessionStorage is used less often than localStorage.

Storage Event

Whenever an update happens to either sessionStorage and localStorage, an event is triggered on all windows that have access to the storage, except the one that caused it.

The following are properties of this event:

  • key the key that was changed (null if .clear() is called).
  • oldValue the old value (null if the key is newly added).
  • newValue the new value (null if the key is removed).
  • url the url of the document where the update happened.
  • storageArea either localStorage or sessionStorage object where the update happened.

Conclusion

Both methods of storing data on the browser have their uses. sessionStorage is more limited, only storing data for the current window. localStorage has more uses, because the data is kept even when the browser closes.

If you liked this article, please share with your friends and consider following me on Medium.

Unlock 10x development with independent components

Building monolithic apps means all your code is internal and is not useful anywhere else. It just serves this one project. And as you scale to more code and people, development becomes slow and painful as everyone works in one codebase and on the same version.

But what if you build independent components first, and then use them to build any number of projects? You could accelerate and scale modern development 10x.

OSS Tools like Bit offer a powerful developer experience for building independent components and composing modular applications. Many teams start by building their Design Systems or Micro Frontends, through independent components. Give it a try →

An independent product component: watch the auto-generated dependency graph

Store Data in the Browser with JavaScript was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Bits and Pieces - Medium and was authored by Pedro Henrique


Print Share Comment Cite Upload Translate Updates
APA

Pedro Henrique | Sciencx (2022-02-15T10:46:17+00:00) Store Data in the Browser with JavaScript. Retrieved from https://www.scien.cx/2022/02/15/store-data-in-the-browser-with-javascript/

MLA
" » Store Data in the Browser with JavaScript." Pedro Henrique | Sciencx - Tuesday February 15, 2022, https://www.scien.cx/2022/02/15/store-data-in-the-browser-with-javascript/
HARVARD
Pedro Henrique | Sciencx Tuesday February 15, 2022 » Store Data in the Browser with JavaScript., viewed ,<https://www.scien.cx/2022/02/15/store-data-in-the-browser-with-javascript/>
VANCOUVER
Pedro Henrique | Sciencx - » Store Data in the Browser with JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/02/15/store-data-in-the-browser-with-javascript/
CHICAGO
" » Store Data in the Browser with JavaScript." Pedro Henrique | Sciencx - Accessed . https://www.scien.cx/2022/02/15/store-data-in-the-browser-with-javascript/
IEEE
" » Store Data in the Browser with JavaScript." Pedro Henrique | Sciencx [Online]. Available: https://www.scien.cx/2022/02/15/store-data-in-the-browser-with-javascript/. [Accessed: ]
rf:citation
» Store Data in the Browser with JavaScript | Pedro Henrique | Sciencx | https://www.scien.cx/2022/02/15/store-data-in-the-browser-with-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.