ReviseAlgo Logo

Browser APIs & Web APIs

localStorage & sessionStorage

Master client-side storage mechanisms in JavaScript. Contrast localStorage and sessionStorage in terms of lifetime scopes, constraints, and events.

Last Updated: July 15, 2026 10 min read

1. Introduction

Web Storage APIs allow web applications to store key-value pairs in the browser. The two primary mechanisms are localStorage (persists indefinitely across browser sessions) and sessionStorage (persists only for the duration of the current page session).

2. Why It Matters

Storing settings (like themes, user interface layouts, or shopping cart selections) on the client side avoids sending unnecessary network requests to a database. Using Web Storage correctly is key to building responsive, fast frontend apps.

3. Real-World Analogy

Think of Office Desk Organizers:

  • localStorage (Personal File Cabinet): A cabinet next to your desk. You lock your files inside. Even if you leave the office for the weekend and turn off the lights, the documents remain in the cabinet until you return and delete them.
  • sessionStorage (Scratchpad on your desk): A temporary notepad. You write down task details for your current meeting. Once you close the folder and leave (close the browser tab), the notepad is thrown away automatically.

4. Web Storage API

Both localStorage and sessionStorage implement the Storage interface, which provides a simple key-value string mapping:

5. Architectural Features

  • String Storage Restriction: Web storage only stores string values. To store objects or arrays, serialize them to JSON strings using JSON.stringify() before storing, and parse them back using JSON.parse().
  • Synchronous Operations: All storage calls are synchronous, which blocks main thread execution during large read/write operations.
  • Origin Restrictions: Storage is isolated per protocol, domain, and port (Same-Origin Policy).
  • Size Limits: Typically capped at 5MB per origin.

6. Comparison Summary

Feature localStorage sessionStorage
Data Lifetime Persistent indefinitely (survives tab/browser closure) Temporary (cleared when tab closes)
Access Scope Shared across all tabs/windows of the same origin Restricted to the active browser tab only
Storage Size Limit ~5MB ~5MB

7. Practical Example

This script demonstrates listening to the storage event, which fires on sibling tabs when another tab modifies localStorage:

8. Common Mistakes

  • Trying to store raw objects directly: Storing an object directly (e.g. localStorage.setItem('key', {id: 1})) serializes it to the string "[object Object]", losing the object's properties. Always use JSON.stringify to serialize objects.
  • Storing sensitive credentials: Storage can be read by any JavaScript running on the page, making it vulnerable to Cross-Site Scripting (XSS) attacks. Never store passwords, tokens, or personal identifiers in localStorage.

9. Quick Quiz

Q1: Which storage mechanism isolates data per browser tab, clearing it when the tab is closed?

A) localStorage

B) sessionStorage

Answer: B — sessionStorage isolates stored data to the current tab and clears it when the tab is closed.

10. Scenario-Based Challenge

The Storage Capacity Safeguard:

Writing values to localStorage throws a QuotaExceededError when storage limits (5MB) are exceeded. Design a robust wrapper helper function saveToStorage(key, data) that catches this exception and alerts developers when the quota is exceeded.

11. Debugging Exercise

Explain why this retrieval script throws a syntax error, and how to fix it:

localStorage.removeItem('user-info'); // ensure empty

// Objective: retrieve user properties const data = JSON.parse(localStorage.getItem('user-info')); // throws syntax error? console.log(data.role);

View Solution

Diagnosis: If the key 'user-info' is missing, localStorage.getItem() returns null. Calling JSON.parse(null) returns null, but then reading data.role throws a TypeError: Cannot read properties of null.

Fix: Add a check to verify the item exists before parsing it or accessing its properties:

const raw = localStorage.getItem('user-info');
const data = raw ? JSON.parse(raw) : null;
if (data) {
  console.log(data.role);
}

12. Interview Questions

🟢 Q1: Compare localStorage, sessionStorage, and cookies in terms of data transport and lifetime.

Answer:
Data Transport: Cookies are sent to the server with every HTTP request, consuming bandwidth. Web Storage (localStorage/sessionStorage) resides strictly in the browser and is never sent to the server.
Lifetime: localStorage persists indefinitely. sessionStorage is cleared when the tab is closed. Cookies persist until their expiration date or session end.
Storage limits: Cookies hold up to 4KB of data. Web Storage holds up to 5MB of data.

13. Production Considerations

  • XSS Vulnerabilities: Never store authentication tokens or passwords in localStorage, because they can be read by any JavaScript running on the page. Use secure, HttpOnly cookies to store sensitive tokens instead.