How browser's local storage works

Updated: 22-Jan-2022 / Tags: Javascript Lang Reference / Views: 540 - Author: George

Introduction

Hello everyone.
In this post we are gonna see how the localStorage Object works. There are times that we want to give the user options on some settings that we have on our website. Such settings maybe are, the language of the document, the theme (light or dark), or hiding some elements.

We could do that with PHP sessions, but as soon as the user closes the browser the setting are set back to their default values.

Here comes localStorage to help us out. With localStorage we can store those settings in the browser. Actually in our hard drive but trough the browser.
And those settings are staying there even if the user closes the browser.

Local Storage

  • The localStorage object is part of the Web Storage API.
  • With the localStorage object we can store data in our browser for a specific domain with no expiration date.
    That means that the data are accessible from all the pages that belongs in the same domain.
  • There is the same origin policy applied. That means that there is no cross domain data transfer.
  • The size of the data that we can store is up to 5MB.
  • The data are stored in a (key, value) pair format, and so its easier to work with.
  • The localstorage object has properties and methods that we can use to store, remove, and fetch data stored in the browser.
  • The data stored in the browser has nothing to do with the server.
  • The user has access to the local storage, and can delete all data stored by the different websites.

Storing data

Lets store some data to see how this works. Lets say we want to store the name of a product, because we want to use that particular product, in a different page, in our website.

localStorage.setItem("product-name", "microphone x series");

To store data in our browser we use the .setItem() method. The .setItem() takes two arguments, the first argument is the key and the second argument is the value.

Here the key is "product-name" and the value is "microphone x series". Remember that the data are stored as key, value pairs.

Every key in our local storage is unique, if we want to store another value with the same key, the previous value will be overridden and the latest value will be stored.

Fetch data

Now to fetch data from the local storage we are gonna use the .getItem() method.

localStorage.getItem("product-name");

When we want to fetch a value from the local storage, we have to pass, in the .getItem() method, the key which holds the value.

This will output the string:

microphone x series

Counting the data

The localStorage Object has a property who counts how many data, (key, value) pairs, are stored in our browser's local storage . This is the .length property.

localStorage.length

This will output the number of the current stored records.

1

Remove data

To remove data from the local storage, we use the .removeItem() method, and we pass in the key of the record we want to delete.

localStorage.removeItem("product-name");

Clear all data

The .clear() method clears all the data that we have in our local storage.
But remember that is only for the current domain.

localStorage.clear();

Storing objects in local storage

Most of the time when we use localStorage , we will store:

  1. javascript objects.
  2. Data coming from a JSON file.
  3. Data from a database.

Lets see how to store a javascript object in our local storage. In the code block bellow we have a javascript object which represents a product.


let product = {
	"product-name": "microphone x series",
	"price": "69.90",
	"image": "mic.png",
	"color": ['blue','red','black']
}

let encodedProduct = JSON.stringify(product);
localStorage.setItem("product", encodedProduct);

 
  • In line 2 - 7 we have an object assigned to a variable named product.

    The product is a microphone and has a product-name, a price, an image, and it comes in three colors ('blue','red','black'), so the color property holds an array.

  • In order to save objects, or arrays, in the local storage, we have to convert them in a JSON string. And for that we use the .stringify() method of the JSON Object.

    So in line 9 we encode the product object to a JSON string which we are storing in the encodedProduct variable.

  • Next in line 10 we use the .setItem() method and we store the encodedProduct with a key of "product" in the local storage.

  • And that's it. The product is stored, and we can use it throughout the whole website.

Fetching the stored object

Next lets see how we can fetch the stored object from the local storage.

let localData = localStorage.getItem("product");
let decodedData = JSON.parse(localData);
  • In line 12 we are fetching the "product" with the .getItem() method and store it in the variable localData. But as we know the localData variable holds now a JSON string.

    {"name":"microphone x series","price":"69.90","image":"mic.png","color":["blue","red","black"]}
  • In line 13 we are using the .parse() method to decode the JSON string back to a javascript object.
    Now we can work with the javascript object as we would normally.

  • If we do a console.log we will see that.

    console.log(decodedData);

    And we see in the console that we have an object

    {name: 'microphone x series', price: '69.90', image: 'mic.png', color: Array(3)}
    color: (3) ['blue', 'red', 'black']
    image: "mic.png"
    name: "microphone x series"
    price: "69.90"
    [[Prototype]]: Object

Summary

  • The localStorage object is part of the Web Storage API.
  • A website can not access an others website's stored data in the local storage.
  • We can store at least 5MB of data.
  • The localstorage object has properties and methods that we can use to store, remove, and fetch data stored in the browser.
  • .setItem() ... stores the data.
  • .getItem() ... fetch the stored key, value pair (record).
  • .removeItem() ... removes a stored record.
  • .clear() ... clears all the stored data in the active domain.
  • .length ... return us the number of the records stored.

And that's it. I hope you liked the post, and thanks for reading.

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal