Physical Address

Sagipora Sopore Baramulla 193201  Jammu & Kashmir

featured image

Web Storage API Explained with Examples

Web Storage is a storage location in our browser that can store data locally on our machine..

Web Storage is a storage location in our browser that can store data locally on our machine. The Web Storage API is a small mechanism that the browser uses to securely store key/value pairs.

  • Key: The identifier of a piece of data.
  • Value: The value corresponding to the defined key.

There are two types of storage in your browser:

  • Local Storage
  • Session Storage

Local Storage: Maintains storage for a given web page for an unlimited period of time until it is deleted.

Session Storage: Maintains storage for a given web page until browser is closed completely.

Related: Fetch API and AXIOS in JavaScript

Web Storage API Basic Usage

We will use localStorage in our examples. For any key/value pair, the value given must be a string. Numbers will be automatically converted into string when stored.

Let’s say we want to remember the theme one user prefers every time they come back to our web page. We can use localStorage for this:

Storing Data

We use the .setItem() method to store a key/value pair. The first parameter of the function is the key and second is the value we assign to it.

localStorage.setItem('appTheme', 'dark')

Accessing Data

We can access the stored data using .getItem() method.

console.log(localStorage.getItem('appTheme')

//dark

Accessing the whole Storage object

console.log(localStorage)

// {appTheme: 'dark', length: 1}

Also Read: JavaScript Higher Order Functions Simplified – map(), reduce() and filter()

Working with Objects

Since we can only store strings inside our browse’s storage, we have to convert any objects we might want to store into a JSON string.

const myData = { name: 'Nasyx', job: 'MERN stack developer' }

localStorage.setItem('user', JSON.stringify(myData))

You can see the changes in your browser’s developer tools under the “Application” tab in Chrome or “Storage” tab in Firefox. Notice how the storage is only kept for the web page where we ran our code.

When you want to read an object that has been stringified, you will need to run JSON.parse() like so:

console.log(JSON.parse(localStorage.getItem('user')))

// {name: 'Nasyx Rakeeb', job: 'MERN stack developer'}

Deleting Data

Data stored using localStorage will not be deleted untill it is deleted manually or the browser’s history is erased.

So in order to delete items, we have two methods:

1. Delete specific item using removeItem()

This method allows you to delete an item by specifying the key that belongs to it.

localStorage.removeItem('appTheme')

2. Clear the entire storage for the active web page

This methodbis straight forward and will erase all key/value pairs entirely from a web page’s local storage.

localStorage.clear()

The Storage Event

Also Read: Latest JavaScript Features Every Web Developer Should Know

We can detect storage changes on a web page by using the storage event listener.

Keep in mind that this event will only triggered when opening two tabs with the same origin, so the same web page. If we make change to the storage in the first tab, the event will trigger in the second tab and all other tabs with the same origin. You can use this event like so:

window.addEventListener('storage', (event) => {
    
    console.log(`Storage event triggered from ${document.title}`)
    
    console.log(event)
})

Output

web storage api

Try it out!

After setting up the event listener, open the same page in two tabs and make change to the storage on the first tab. The event will be trigger in the second tab.

web storage api

Other Facts

Also Read: What is Call Stack In Javascript And Why Its Important

  • When browsing privately (incognito), localStorage will aslo get empty when you close the browser, in the same way as sessionStorage is deleted.
  • With little setup, localStorage can be used successfully as small database for basic practice projects and you can implement a full CRUD functionality using it.
  • The browser’s web page storage is actually an object, so you can treat it like one and perform different actions. However, it is best to use the setItem() and getItem() methods to avoid possible problems.

Related Link

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *

Programming & Tech Digest
Programming and Tech innovations delivered straight to your inbox for free.