← Back to HTML Course | Chapter 7: Advanced APIs & Features | Lesson 5 of 11

HTML Web Storage

Imagine visiting an online bookstore. You add a couple of books to your cart, but then you accidentally close the tab. When you re-open the page, you expect to find your books still sitting in your cart, ready to purchase. HTML Web Storage does exactly that. It is a secure, built-in storage container inside your browser that lets websites save small pieces of data (like settings, themes, or cart items) directly on your device. Unlike traditional cookies, web storage is much faster, more secure, and can hold much more data without slowing down your website.

What is Web Storage?

Web Storage is a standard browser API designed to save data locally as simple key-value pairs. It replaces traditional cookies for storing non-sensitive data, offering faster performance, better security, and a much larger storage capacity (up to 5MB).

Note: Only use web storage to save non-sensitive settings; never store sensitive data like passwords or credit card numbers.

Warning: Web storage data is saved as plain text inside the browser, making it accessible to anyone with access to the device.

Example: What is Web Storage?

markup
<script>
  localStorage.setItem('username', 'Alex');
</script>

Persistent Storage with localStorage

The localStorage object saves data persistently on the user's device. This data has no expiration date; it remains saved even when the user closes their tabs, restarts their browser, or shuts down their device.

Note: Use localStorage to save user preferences like dark mode settings so they persist across visits.

Warning: Avoid overusing localStorage as it can fill up the browser's storage quota if not managed.

Example: Persistent Storage with localStorage

markup
<script>
  localStorage.setItem('theme', 'dark');
  console.log(localStorage.getItem('theme'));
</script>

Temporary Storage with sessionStorage

The sessionStorage object works exactly like localStorage, but it is temporary. The data is only saved for the duration of the page session, meaning it is deleted as soon as the user closes their browser tab.

Note: Use sessionStorage to store temporary form progress or single-session analytics data.

Warning: Data stored in sessionStorage will be lost if the user duplicates or closes the active tab.

Example: Temporary Storage with sessionStorage

markup
<script>
  sessionStorage.setItem('formProgress', 'step2');
  console.log(sessionStorage.getItem('formProgress'));
</script>

Saving Structured Data using JSON

Web Storage can only store data as simple strings. To save complex data structures (like arrays or objects), you must convert them into a JSON string using JSON.stringify before saving, and parse them back using JSON.parse when retrieving.

Note: Use JSON encoding to save complex arrays of user settings or search histories in a single key.

Warning: Attempting to save raw JavaScript objects directly without converting them to JSON will result in saving an unreadable '[object Object]' string.

Example: Saving Structured Data using JSON

markup
<script>
  const settings = { theme: 'dark', fontSize: 16 };
  localStorage.setItem('settings', JSON.stringify(settings));
  const saved = JSON.parse(localStorage.getItem('settings'));
</script>

Clearing and Managing Storage Space

To keep your storage space organized and stay within browser limits, you should regularly clear out old or unused data. You can delete specific items using removeItem, or clear the entire storage area using the clear method.

Note: Provide a simple reset button on your page to let users clear their saved preferences easily.

Warning: Calling the clear method will delete all data stored by your website, so use it carefully.

Example: Clearing and Managing Storage Space

markup
<script>
  localStorage.removeItem('theme');
  localStorage.clear();
</script>

Storage Limits Per Browser

Most modern browsers allow around 5 to 10 megabytes of storage per origin for both localStorage and sessionStorage, though the exact limit varies slightly between Chrome, Firefox, and Safari. This is plenty for settings and small cached data, but far too little for storing large files or media.

Note: For anything larger than a few megabytes, look into IndexedDB instead, which supports much larger storage quotas.

Warning: Exceeding the storage limit throws a QuotaExceededError, which will crash your script if you are not catching it.

Example: Storage Limits Per Browser

markup
<script>
  try {
    localStorage.setItem('data', 'x'.repeat(10000000));
  } catch (e) {
    console.log('QuotaExceededError:', e.message);
  }
</script>

Listening for Storage Events

The storage event fires on other open tabs or windows of the same site whenever localStorage changes in one of them, letting you keep multiple tabs in sync. Notably, this event does not fire in the same tab that made the change, only in other tabs listening to the same origin.

Note: Use the storage event to sync things like a logged-in state or shopping cart across multiple open tabs of your site instantly.

Warning: Because the storage event does not fire in the tab that made the change, you cannot use it to detect changes made by your own current tab's script.

Example: Listening for Storage Events

markup
<script>
  window.addEventListener('storage', function (event) {
    console.log(event.key, event.newValue);
  });
</script>

Cookies vs localStorage

Cookies are automatically sent to the server with every single HTTP request, have a much smaller size limit around 4 kilobytes, and can have an expiration date. localStorage never gets sent to the server automatically, holds far more data, and persists until explicitly cleared, making it much better suited for client-only data like UI preferences.

Note: Use cookies only for data the server genuinely needs to see, like authentication tokens, and use localStorage for everything that is purely for the browser's own use.

Warning: Storing sensitive data in localStorage is not inherently safer than cookies — both are readable by any JavaScript running on the page, so neither should hold plain sensitive secrets.

Example: Cookies vs localStorage

markup
<script>
  document.cookie = "token=abc123";
  localStorage.setItem('uiTheme', 'dark');
</script>
Common Mistakes
  1. Storing sensitive user passwords or payment details in web storage, leaving them vulnerable to theft.
  2. Attempting to save raw JavaScript objects directly without converting them to JSON strings first.
  3. Exceeding the browser's 5MB storage limit, causing your save scripts to throw errors and fail.
Chapter Summary
  • Web Storage allows websites to save data locally inside the user's browser as key-value pairs.
  • Use localStorage to save persistent data that never expires, and sessionStorage for temporary, session-bound data.
  • Convert complex data structures (like arrays or objects) to JSON strings before saving, and parse them back when retrieving.
Browser Support

Standard Web Storage APIs are supported natively by all modern web browsers.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.