HTML - HTML5 Web Storage API (Local Storage & Session Storage)

Image

The HTML5 Web Storage API allows websites to store data directly in the browser. This data is saved as key–value pairs and is much simpler and faster than cookies. Web Storage is mainly used to store user preferences, login state (non-sensitive), themes, and temporary app data.

There are two types of Web Storage: localStorage and sessionStorage. Both store data in the browser, but the difference is how long the data lasts.


1. Local Storage (localStorage)

localStorage stores data permanently until it is manually deleted by the user or cleared by code. Even if the browser is closed or the system is restarted, the data remains.

Key points:

  • Data persists after browser close

  • Storage limit ~5–10 MB

  • Data is stored as strings

  • Same data available across tabs (same origin)

Example:

<script>
  localStorage.setItem("username", "Vidhi");
  let user = localStorage.getItem("username");
  console.log(user);
</script>

Use cases:

  • Dark/light mode preference

  • Language selection

  • Remembering user settings


2. Session Storage (sessionStorage)

sessionStorage stores data only for one browser tab. Once the tab is closed, the data is automatically removed.

Key points:

  • Data cleared when tab closes

  • Unique per tab

  • Same size limit as localStorage

  • More secure for temporary data

Example:

<script>
  sessionStorage.setItem("page", "checkout");
  let page = sessionStorage.getItem("page");
  console.log(page);
</script>

Use cases:

  • Form progress

  • Temporary user state

  • One-time session data


Local Storage vs Session Storage (Quick Comparison)

Feature localStorage sessionStorage
Data lifetime Permanent Until tab closes
Shared across tabs Yes No
Storage size Large Large
Best for Preferences Temporary data

Important Security Note

Web Storage is not encrypted. Never store passwords, OTPs, or sensitive personal data. It is meant only for non-critical information.

  • localStorage = long-term browser storage

  • sessionStorage = short-term tab-based storage
    Both are fast, simple, and essential for modern web applications.