HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

Web Storage API

The Web Storage API is a modern, faster, and more secure way to store data on the client side compared to cookies. It allows web applications to store up to 5MB of data as key-value pairs directly in the user's browser.


Storage Dashboard

Try saving data to your browser's persistent storage. The data will remain even if you refresh the page!

LocalStorage (Persistent)
Retrieved Message: None

localStorage vs sessionStorage

The Web Storage API provides two mechanisms for storing data, differing only in their lifespan:

1. localStorage

Data has **no expiration date**. It survives browser restarts and computer reboots. It remains until explicitly deleted via code or cleared by the user.

2. sessionStorage

Data is **temporary**. It is deleted when the specific browser tab or window is closed. Each tab has its own isolated session storage.


Common Storage Methods

Both storage types use the same set of simple methods for data manipulation:

1. Saving Data (setItem)

// Syntax: storage.setItem(key, value)
localStorage.setItem("theme", "dark");
sessionStorage.setItem("user_id", "404");

2. Retrieving Data (getItem)

// Syntax: storage.getItem(key)
let myTheme = localStorage.getItem("theme");
console.log(myTheme); // "dark"

3. Removing Data (removeItem / clear)

// Remove one specific item
localStorage.removeItem("theme");

// Wipe the entire storage for this domain
localStorage.clear();

Storage Comparison Table

Feature LocalStorage SessionStorage Cookies
Expiry Never Tab closing Custom / Closure
Capacity 5MB - 10MB 5MB 4KB
Server Side No access No access Included in Headers
Tip: Web Storage only stores strings. To store objects or arrays, use JSON.stringify() when saving and JSON.parse() when retrieving.

Key Points to Remember

  • Web Storage is easier and larger than cookies.
  • Use localStorage for user preferences and settings.
  • Use sessionStorage for one-time sessions or multi-step forms.
  • The API is synchronous; huge amounts of storage read/writes might block the UI.
  • Data is scoped to the **origin** (Domain + Protocol).
  • To view your storage, open F12 DevTools $\rightarrow$ **Application** tab.