Thursday, May 23, 2024

Easy Guide to Using LocalStorage with JavaScript

The API called Web Storage provides two basic mechanisms for storing information in a user’s browser: sessionStorage and localStorage. The sessionStorage (which we won’t address in this article) works much like localStorage, but with one difference: it keeps the data recorded only until the end of the user’s session, i.e. until the user’s browser closes including reloads from the session, page or restores. The localStorage keeps the recorded data even if the browser is closed and reopened. This makes it easy to create some interface behaviors while using the user. And obviously, needless to say, it is not meant to record sensitive data.

The data storage structure is very simple, consisting of the key and value pair. An example:

  key: 'value';

To work with this data, you can basically do 4 actions using 4 methods:

  • localStorage.setItem() to create a new key pair: value
  • localStorage.getItem() to retrieve the value of the key pair: value
  • localStorage.removeItem() to remove a specific pair
  • localStorage.clear() erases ALL pairs recorded for that domain

It has a method called key(). But I won’t talk about that here to simplify the explanations.

Viewing localStorage in Inspect

To see all data recorded in your browser’s localStorage, just open inspect, click on the Application tab, and then on the sidebar, click Local Storage (path using Chrome or Chromium engine browsers).

Your localStorage, when recorded, will be there, within the address of the website you are working on.

Writing Data: localStorage.setItem()

This method allows you to write values into localStorage in the user’s browser.

Take a look at the following example shown at Listing 1.

Listing 1. Example of localStorage item setting

Save Item

// CSS
span {
  cursor: pointer;
  background: rgba(0, 0, 0, .2);
  font: 16px sans-serif;
  padding: 5px 10px;
  border-radius: 15px;
  font: 15px sans-serif;

// JS
(function (){
  'use strict';

  var btnSetItem = document.querySelector('.btnSetItem')

  function setLocalStorage(){
     btnSetItem.addEventListener('click', () => {
      localStorage.setItem('name','Keanu Reeves')


Open Inspector now, go to where LocalStorages are stored. You will see our name: ‘Keanu Reeves’ saved (Figure 1).

LocalStorage Figure01
Figure 1. Checking out the name saved in Local Storage.

Note: Note that the values will always be a string. Therefore, the data that will be written there needs to be converted to strings before it can be written. To do this, simply use the JSON.stringify() method before passing the value to setItem().

Now that we have written the value to the user’s browser, we will now retrieve it using the localStorage.getItem() method.

Retrieving Data: localStorage.getItem()

Working very similarly to setItem(), we’ll use getItem() to retrieve the value of a previously recorded key. In our case, we’ll use it to get the name key we recorded in the setItem() example.

function getLocalStorage() {
  btnGetItem.addEventListener('click', () => {

Click in the GET button and then Catch. Note that in console.log(), we put the value that was recorded earlier.

Removing Data: localStorage.removeItem()

Once we no longer use this data, it is good practice to delete locaStorage, thus avoiding unnecessary data accumulation.

The removeItem() method will delete the key you set. If the key does not exist, it will do nothing.

function removeLocalStorage() {
  btnRemoveItem.addEventListener('click', () => {

The removeItem() removes only the key (or object) you requested. Have localStorage.clear() to erase ALL keys of your domain. You do not need to pass any parameters.

Cautions, Safety and Limitations

Some cautions and limitations when using localStorage:

  • Do not use localStorage to store sensitive data
  • The data that is recorded has no layer of access protection, that is, all data recorded there can be accessed by any code on your page
  • In any browser, localStorage is limited to storing only 5Mb of data. Much more than the 4Kb of cookies
  • The use of localStorage is synchronous, that is, all execution is only done one after another
  • You can only use strings in localStorage, and that’s a pain, because it limits the writing of more complex data and if you try to do any conversion it turns into a boundless gamble
  • Cannot be used by web workers. This means that if you want to make more complex applications using background processing to improve performance, you will not be able to use localStorage because it is not available.

Ideally, you should use localStorage for situations where you want to record data that may be public, non-sensitive, not used in more complex applications, no larger than 5MB and strings only.

For simple interface stuff that doesn’t make much sense to write something to the database or somewhere in a more permanent way, it’s nice to use localStorage. If you are creating a SPA or any site/system and want some server independence, using localStorage is appropriate and very useful.

More Security

One more word about security: any JavaScript running on your domain, on your pages, can access the data you recorded on localStorage. Well, you might think, “But I control the JS I put on the page.” And yes, that’s true… But if you use any script, plugin, framework, library, and anything else, you’re at a bigger risk.

Please, refer to the official docs for more about localStorage and security information.

btnSetItem.addEventListener('click', () => {
      localStorage.setItem('name','Keanu Reeves')

About the Author

Diogo Souza works as a Java Developer at PagSeguro and has worked for companies such as Indra Company, Atlantic Institute and Ebix LA. He is also an Android trainer, speaker at events on Java and mobile world.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles