Skip to content
nive.sh

Loading index…

↑↓ navigate · ↵ opennive.sh

A Practical guide to use LocalStorage and SessionStorage

SessionStorage and LocalStorage are a simple key/value pair storage and only the string type of data can be stored. SessionStorage and LocalStorage both has same API. Both storage objects provide same methods and properties.

Nivesh Saharan

· 3 min read · 568 words

SessionStorage

SessionStorage is a simple key/value pair storage and only the string type of data can be stored. It is a tab specific storage and the data stored in SessionStorage will be lost when that tab is closed. We can store upto 5MB of data in this storage. Data stored in SessionStorage cannot be accessed from another tab.

LocalStorage

LocalStorage is also a simple key/value pair storage and only the string type of data can be stored. The data stored in LocalStorage is shared between all tabs for same domain. There is no expirations for the data in LocalStorage so it is always there even if you close the tabs or restart your system.

Check if the browser supports it

if(typeof(Storage) !== void(0))
{
  // Your browser support localStorage and sessionStorage
}
else{
  // Sorry! No web storage support..
}

Storage API

SessionStorage and LocalStorage both has same API. Both storage objects provide same methods and properties. Following examples shows the API usage for localStorage and since they use same API, feel free to replace localStorage with sessionStorage

Store an Item

// Store a simple string
localStorage.setItem('my-key', 'my-value');
 
// Store an object (Must be converted to string)
localStorage.setItem('my-object-key', JSON.stringify({key: 'value'}));

Get an Item from Storage

localStorage.getItem('my-key'); // Returns string: 'my-value'
 
localStorage.getItem('my-object-key'); // Returns string: '{"key":"value"}'
 
JSON.parse(localStorage.getItem('my-object-key')); // Returns object: {key:"value"}

Remove an item

localStorage.removeItem('my-key');

The number of stored items

localStorage.length // Return count of items stored

Get the key on a given position

localStorage.key(0); // Returns key of the item at very first position

Get all keys

Object.keys(localStorage); // Returns array of all keys

Get all items

for(let i = 0; i < localStorage.length; i++){
  const key = localStorage.key(i);
  const value = localStorage.getItem(key);
  console.log(key, value)
}

Remove everything from storage

localStorage.clear(); // Removes everything from localStorage

Storage Event

When the data gets updated in LocalStorage or SessionStorage, the storage event is triggered with following properties:

  • key - The name of key that was changed. (It will be null if .clear was called)
  • oldValue - The old value of changed key. (It will be null if it is newly added)
  • newValue - The new value of changed key. (It will be null if the key was removed)
  • url - The URL where the change happened
  • storageArea - localStorage object or sessionStorage object depending on where it was updated.

Storage event is triggered on all window objects of same domain excepts the one that triggered it.

Listen for events

window.addEventListener('storage', function(e){
  console.log(e.key, e.oldValue, e.newValue, e.url, e.storageArea)
});

Storage event triggered when the value is actually changed. Setting same value won't trigger the event.

Listen for a specific key change

window.addEventListener('storage', function(e){
  if(e.key === 'my-key')
  {
    // Do your thing
  }
});

Things to remember

  • LocalStorage and SessionStorage allow to store key/value (String only).
  • Storage event triggers on setItem, removeItem, clear calls.
  • The event triggers on all window objects where the storage is accessible, except the one that caused it.
  • Refreshing the page doesn't remove data from SessionStorage
  • Closing the browser or rebooting your system doesn't remove data from LocalStorage
  • Do not store sensitive user information in LocalStorage or SessionStorage

Keep reading

Related articles

All articles

Jun 27, 2023 · 5 min read

Arrays and Tuples

There are two primitive compound types in Rust: Arrays and Tuples.

  • JavaScript
  • Rust

Jun 26, 2023 · 4 min read

A Practical guide to use Arrays and Objects in JavaScript

JavaScript objects and arrays are fundamental data structures used to organize and store data. In this comprehensive guide, we will explore the concepts of objects and arrays, provide relatable examples for both technical and non-technical individuals, and delve into safe techniques for copying and modifying these data structures. By following the discussed techniques, you can ensure data integrity, avoid unintended side effects, and confidently work with JavaScript data.

  • javascript

Jun 23, 2023 · 3 min read

Hello, Rust!

Welcome to Rust for JavaScript Developers! It's fantastic to have you here. Let's dive right in.

  • JavaScript
  • Rust

Newsletter

Build notes, when there is something worth sending.

New deep-dive articles and the occasional note on what I am shipping. No schedule, no filler, unsubscribe any time.

Taking on new projects

Need help with custom web and mobile engineering?

Tell me about the storefront, product or platform you’re working on. A 30-minute call is usually enough to map the first steps.

Email

hey@nive.sh

Local time

--:-- · Gurugram (IST)