Frontend Development 15 min read

Understanding localStorage and sessionStorage: Differences, Compatibility, APIs, and Best Practices

This article explains the concepts, differences, browser compatibility, APIs, storage limits, performance considerations, and practical applications of localStorage and sessionStorage in web development, providing code examples and best‑practice guidelines for using browser storage effectively.

转转QA
转转QA
转转QA
Understanding localStorage and sessionStorage: Differences, Compatibility, APIs, and Best Practices

1. Introduction

Browser local storage provides a mechanism for web applications to store data on the client side, allowing fast retrieval on subsequent visits. There are two storage types: localStorage and sessionStorage . This article introduces their characteristics and internal platform usage.

2. localStorage and sessionStorage

2.1 Differences

The main difference lies in their lifecycle. The comparison table below summarizes the key points:

localStorage

sessionStorage

Lifecycle

Persistent until explicitly removed or cleared

Session‑level; cleared when the tab or window is closed

Scope

Same browser, same origin, different tabs/windows

Same browser, same origin, same window

Access method

window.localStorage
window.sessionStorage

Capacity

5 MB

5 MB

The capacity limit prevents abuse of local storage space, which could otherwise slow down the browser.

2.2 Browser Compatibility

Modern browsers generally support both storage types. Compatibility matrix:

Chrome

Firefox

IE

Opera

Safari

Android

Opera Mobile

Safari Mobile

localStorage

4

3.5

8

10.5

4

2.1

11

iOS 3.2

sessionStorage

5

2

8

10.5

4

2.1

11

iOS 3.2

For legacy browsers (e.g., IE 6/7), detection is required before using storage:

if (window.localStorage) {
  alert("Browser supports localStorage");
} else {
  alert("Browser does not support localStorage");
}

When storage operations may fail, wrap them in try/catch :

if (window.localStorage) {
  try {
    localStorage.setItem("username", "name");
    alert("Browser supports localStorage");
  } catch (e) {
    alert("Browser supports localStorage but cannot use it");
  }
} else {
  alert("Browser does not support localStorage");
}

3. Usage Guide

3.1 API Overview

Both storages share the same API for setting, getting, and removing data. Common methods:

Set data: setItem(key, value)

Get data: getItem(key)

Delete data: removeItem(key)

Clear all: clear()

Check existence: hasOwnProperty(key)

List keys: Object.keys(storage)

Values must be strings; objects/arrays should be serialized with JSON.stringify and parsed with JSON.parse when retrieved.

localStorage.setItem("username", "name"); // "name"
localStorage.setItem("count", 1); // "1"
localStorage.setItem("isOnline", true); // "true"
const user = { "username": "name" };
localStorage.setItem("user", JSON.stringify(user));

Getting data returns a string; deserialize as needed:

const usernameLocal = localStorage.getItem("username");
const userLocal = JSON.parse(localStorage.getItem("user"));

3.2 Viewing in Browser

Open DevTools (F12), go to the Application tab, and locate localStorage or sessionStorage under the Storage section.

3.3 Listening to Changes

The storage event fires in other pages of the same origin when a storage item changes. Example:

window.addEventListener("storage", (e) => {
  if (e.key === "username") {
    console.log("username old: " + e.oldValue + ", new: " + e.newValue);
  }
});

To listen within the same page, override the native methods and dispatch custom events:

(() => {
  const originalSetItem = localStorage.setItem;
  localStorage.setItem = function (key, val) {
    const event = new Event("setItemEvent");
    event.key = key;
    event.newValue = val;
    window.dispatchEvent(event);
    originalSetItem.apply(this, arguments);
  };
})();

window.addEventListener("setItemEvent", function (e) {
  if (e.key === "username") {
    const oldValue = localStorage.getItem(e.key);
    console.log("username old: " + oldValue + ", new: " + e.newValue);
  }
});

4. Storage Capacity and Performance

Browsers typically allocate up to 5 MB per origin, but the actual limit depends on available disk space.

4.1 Measuring Capacity

Use the length property or attempt to write data until an exception occurs:

let str = "0123456789";
while (str.length !== 10240) { // generate 10 KB string
  str += "0123456789";
}
localStorage.clear();
const computeTotal = () => new Promise((resolve) => {
  const timer = setInterval(() => {
    try {
      localStorage.setItem("temp", str);
    } catch (e) {
      resolve(str.length / 1024); // KB used
      clearInterval(timer);
      localStorage.clear();
    }
  }, 0);
});

Running the script in Chrome shows a maximum capacity of about 5 MB.

4.2 Performance Tips

When storing large data, consider:

Compressing data (e.g., using lz-string ).

Splitting large payloads into smaller chunks.

Removing unnecessary data.

Implementing expiration logic, since localStorage has no native TTL.

// Example: compression with lz-string
const LZString = require("lz-string");
const data = "This is a test message";
const compressed = LZString.compress(data);
localStorage.setItem("test", compressed);
const decompressed = LZString.decompress(localStorage.getItem("test"));

5. Practical Applications

5.1 Recording User Preferences

Cache filter selections or user habits to avoid repeated actions. Example: storing a favorite flag.

// Retrieve
const isFavor = localStorage.getItem('isFavor');
this.state = { isFavor: isFavor !== null ? Number(isFavor) : EngineeringTypeEnum.FAVOR };
// Update
changeFavor = (e) => {
  localStorage.setItem('isFavor', e);
  this.setState({ isFavor: e });
};

5.2 First‑Visit Tips

Show a guide modal only on the first visit or after cache clearance.

// Retrieve flag
const operationVisible = localStorage.getItem('operationVisible');
this.state = { operationVisible: operationVisible === null || operationVisible === 'true' };
// Hide modal and persist
onCancel={() => {
  this.setState({ operationVisible: false });
  localStorage.setItem('operationVisible', false);
}}

5.3 Reducing Repeated API Calls

Cache immutable data such as user IDs in localStorage to avoid unnecessary network requests.

6. Conclusion

This article provided an overview of Web Storage, covering lifecycle differences, compatibility, API usage, capacity limits, performance considerations, and real‑world scenarios. Proper handling of storage operations can improve user experience, but developers must be aware of size limits, serialization requirements, and error handling.

frontendJavaScriptlocalStoragesessionStorageweb storage
转转QA
Written by

转转QA

In the era of knowledge sharing, discover 转转QA from a new perspective.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.