Frontend Development 15 min read

Understanding and Using localStorage and sessionStorage in Web Development

This article provides a comprehensive overview of browser localStorage and sessionStorage, covering their differences, compatibility, API usage, storage limits, performance tips, and practical applications such as habit tracking, first‑open prompts, and reducing redundant API calls.

Zhuanzhuan Tech
Zhuanzhuan Tech
Zhuanzhuan Tech
Understanding and Using localStorage and sessionStorage in Web Development

1. Introduction

Browser local storage is a mechanism that allows web applications to store data on the client side so that it can be quickly retrieved on subsequent visits. There are two storage types: localStorage and sessionStorage . This article introduces their characteristics and internal platform use cases.

2. localStorage and sessionStorage

2.1 Differences

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

localStorage

sessionStorage

Lifecycle

Persistent until explicitly removed or cleared

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

Scope

Same browser, same origin, across tabs and 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 versions are shown below:

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

If you need to support older browsers (e.g., IE 6/7), detect support before using the API:

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

Wrap calls in try/catch to handle unexpected failures:

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

3. Usage Guide

3.1 API Overview

Both localStorage and sessionStorage share the same methods for storing, retrieving, and deleting data:

Set data: setItem(key, value)

Get data: getItem(key)

Remove data: removeItem(key)

Clear all: clear()

Check existence: hasOwnProperty(key)

List keys: Object.keys(storage)

Values must be strings; use JSON.stringify and JSON.parse for objects and arrays.

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

3.2 Viewing Storage in the Browser

Open developer tools (F12) → Application → Storage to inspect localStorage and sessionStorage entries.

3.3 Listening to Changes

The storage event fires in other tabs when a storage item changes. Example for cross‑tab listening:

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

Note that the event does not fire when the same value is set again, and it only works for localStorage .

To listen within the same page, override setItem and dispatch a custom event:

(() => {
  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 Limits

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

4.1 Capacity Measurement

You can estimate used space with Storage.length and by summing the length of each stored value:

let str = "0123456789";
let temp = "";
while (str.length !== 10240) { // generate 10 KB string
  str += "0123456789";
}
localStorage.clear();
const computedTotal = () => new Promise(resolve => {
  const timer = setInterval(() => {
    try {
      localStorage.setItem("temp", temp);
    } catch (e) {
      resolve(temp.length / 1024); // KB
      clearInterval(timer);
      localStorage.clear();
    }
    temp += str;
  }, 0);
});
const computedUse = () => {
  let cache = 0;
  for (let key in localStorage) {
    if (localStorage.hasOwnProperty(key)) {
      cache += localStorage.getItem(key).length;
    }
  }
  return (cache / 1024).toFixed(2); // KB
};
(async () => {
  const total = await computedTotal();
  let use = "0123456789".repeat(1000);
  localStorage.setItem("use", use);
  const useCache = computedUse();
  console.log(`Maximum capacity ${total}KB`);
  console.log(`Used ${useCache}KB`);
  console.log(`Remaining ${total - useCache}KB`);
})();

4.2 Performance Considerations

Storing large amounts of data can block the main thread. Recommended strategies:

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

Split large data into smaller chunks.

Store only necessary information.

Implement expiration logic manually, since localStorage has no built‑in TTL.

Example of compression:

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"));

Example of splitting data:

for (const key in userInfo) {
  localStorage.setItem(key, userInfo[key]);
}

Example of expiration wrapper:

function set(key, value) {
  const time = Date.now();
  localStorage.setItem(key, JSON.stringify({ value, time }));
}
function get(key, exp) { // exp in ms
  const item = JSON.parse(localStorage.getItem(key));
  if (Date.now() - item.time > exp) {
    console.log("expires");
  } else {
    console.log("value:" + item.value);
  }
}

5. Practical Applications

5.1 Recording User Habits

Cache filter selections or user preferences to avoid repeated operations. Example: store a favorite flag for a project list.

const isFavor = localStorage.getItem('isFavor');
this.state = {
  isFavor: isFavor !== null ? Number(isFavor) : EngineeringTypeEnum.FAVOR,
};
// In the UI, bind the value to a Select component and update on change
localStorage.setItem('isFavor', e);
this.setState({ isFavor: e });

5.2 First‑Open Prompt

Show a guide modal only once per user or after the cache is cleared.

const operationVisible = localStorage.getItem('operationVisible');
this.state = {
  operationVisible: operationVisible === null || operationVisible === 'true' ? true : false,
};
// When the modal is closed
localStorage.setItem('operationVisible', false);

5.3 Reducing Duplicate API Calls

Cache static data such as user IDs that do not change frequently, allowing other pages to read from localStorage instead of repeatedly calling the backend.

6. Conclusion

This article aimed to help readers understand how to use Web Storage APIs for data persistence, event handling, and performance considerations. Proper use can improve user experience by storing preferences, form data, and cacheable resources, while being mindful of storage limits and error handling.

frontendJavaScriptlocalStoragesessionStorageweb storage
Zhuanzhuan Tech
Written by

Zhuanzhuan Tech

A platform for Zhuanzhuan R&D and industry peers to learn and exchange technology, regularly sharing frontline experience and cutting‑edge topics. We welcome practical discussions and sharing; contact waterystone with any questions.

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.