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

Pedro Henrique
Bits and Pieces

--

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.

💡 Tip: You can use Bit to share and reuse your localStorage/sessionStorage logic as utility functions between apps. Create a module that exports your getItem/setItem/removeItem functions, and then publish the module to Bit. This way, you’ll have access to those functions wherever you need them with a simple npm i @bit/your-username/your-storage-module and an import, and have independent versioning, tests, and documentation for them too. No more copy/pasting repeatable code between repos.

Learn more here:

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.

Build Apps with reusable components, just like Lego

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo

--

--

I am a Brazilian data engineer working out of Stockholm. when I am not thinking on ways to move data around, I enjoy riding motorcycles and reading books.