Back to roadmaps html Course
Table of Contents (31 guides)

Web Storage API: LocalStorage and SessionStorage Explained

Often, web applications need to save simple configurations (like dark mode state, user preferences, or active shopping carts) without hitting a backend database. HTML5 provides the Web Storage API to do exactly this.


1. LocalStorage vs. SessionStorage

The Web Storage API consists of two mechanisms: localStorage and sessionStorage. They share the same methods but differ in data lifetimes:

Feature localStorage sessionStorage
Data Lifetime Persistent (lasts forever until manually deleted) Temporary (cleared when the browser tab is closed)
Tab Sharing Shared across all tabs/windows of the same domain Restricted to the single, specific browser tab
Storage Cap ~5MB (Per origin/domain) ~5MB (Per origin/domain)

2. Using Web Storage Methods

Both mechanisms use four simple methods to manage data:

A. Writing Data: setItem()

Stores key-value pairs. Note that Web Storage only stores string data.

// Stores a simple string
localStorage.setItem('theme', 'dark');

B. Reading Data: getItem()

Retrieves stored string data using its key name. Returns null if the key does not exist.

const userTheme = localStorage.getItem('theme'); // returns 'dark'

C. Deleting Specific Data: removeItem()

Deletes a single key-value pair from storage.

localStorage.removeItem('theme');

D. Clearing All Data: clear()

Deletes all key-value pairs stored under the current domain.

localStorage.clear();

3. Working with Complex Data (JSON)

Since Web Storage only accepts strings, you must convert JavaScript arrays and objects to strings before saving them, and parse them back when reading.

Storing an Object:

const userProfile = {
  name: 'Sarah',
  theme: 'dark',
  completedTutorials: [1, 3]
};

// Convert to string and save
localStorage.setItem('profile', JSON.stringify(userProfile));

Retrieving an Object:

const rawData = localStorage.getItem('profile');

if (rawData) {
  // Parse back to JavaScript object
  const profile = JSON.parse(rawData);
  console.log(profile.name); // outputs 'Sarah'
}

4. Key Limitations and Security Notes

  • Never store sensitive data: LocalStorage is easily readable via browser extensions or malicious cross-site scripting (XSS) scripts. Do not use it to store user passwords, credit card numbers, or session JWT tokens.
  • Synchronous nature: Web Storage operations run synchronously, meaning excessive reads/writes can block the main browser thread. Use it only for small configurations.
Published on