HTML Local Storage

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples + 3 Try It
localStorage

Introduction

Local Storage is a feature of the Web Storage API that allows websites to store key-value pairs in a web browser, persisting even after the browser is closed. It is an ideal solution for storing small amounts of data that should remain available across sessions.

Unlike cookies, data stored in Local Storage is not sent with every HTTP request, making it more efficient for storing client-side data such as theme preferences, UI settings, or a shopping cart between visits.

What You’ll Learn

01

setItem

Save strings.

02

getItem

Read values.

03

removeItem

Delete one key.

04

clear

Wipe all data.

05

JSON

Store objects.

06

Limits

Size & security.

What Is Local Storage?

Local Storage is a part of the browser’s Web Storage API that allows you to store data locally on the user’s computer.

Data stored in Local Storage does not expire unless explicitly removed, making it persistent even when the browser or device is restarted.

It stores data as key-value pairs and is particularly useful for saving user preferences, theme settings, or lightweight app state across visits.

💡
Beginner Tip

Think of localStorage as a simple notepad tied to your website’s domain. Every page on example.com can read and write the same keys.

Key Features of Local Storage

  • Key-Value Storage — stores data as simple key-value pairs.
  • Persistent Storage — data remains available across browser sessions.
  • Synchronous API — all operations are synchronous, unlike IndexedDB.
  • Limited Size — each domain can typically store up to 5 MB of data.
  • No Expiration — data persists until manually deleted by the application or the user.

How to Use Local Storage

Local Storage is easy to use with JavaScript. You interact with it using the localStorage object, which provides methods to store, retrieve, and remove data. The data is stored as strings, so you need to stringify objects before storing them.

The four essential methods mirror sessionStorage:

  • localStorage.setItem(key, value) — save a string
  • localStorage.getItem(key) — read a string (or null)
  • localStorage.removeItem(key) — delete one entry
  • localStorage.clear() — delete every key for this origin

Setting Data in Local Storage

To store data in Local Storage, you can use the setItem method. Here’s how you can store a simple key-value pair:

js
localStorage.setItem('username', 'JohnDoe');

You can also store objects, but since Local Storage only stores strings, you’ll need to use JSON.stringify:

js
var user = { name: 'JohnDoe', age: 30 };
localStorage.setItem('user', JSON.stringify(user));

Retrieving Data from Local Storage

To retrieve data, use the getItem method:

js
var username = localStorage.getItem('username');
console.log(username); // JohnDoe

If you are retrieving an object, you will need to parse it back into its original form using JSON.parse:

js
var user = JSON.parse(localStorage.getItem('user'));
console.log(user.name); // JohnDoe

Removing Data from Local Storage

If you want to remove a specific item from Local Storage, use the removeItem method:

js
localStorage.removeItem('username');

All Data in Local Storage

You can clear all the data stored in Local Storage for your domain by using the clear method:

js
localStorage.clear();

Use clear() carefully—it removes every key your site saved on this origin, not just one feature’s data.

Limitations of Local Storage

  • Size Limit — the amount of data you can store is limited (typically around 5 MB per domain).
  • Synchronous API — all Local Storage operations are blocking, which may impact performance if used improperly on large values.
  • Security Risks — data stored in Local Storage is not encrypted, so sensitive information should not be stored.
  • Same-Origin Policy — Local Storage data is accessible only within the same domain and protocol.

localStorage vs sessionStorage

FeaturelocalStoragesessionStorage
LifetimeUntil cleared manuallyUntil tab closes
Shared across tabsYes (same origin)No (per tab)
Survives browser restartYesNo
Typical useTheme, prefs, cartWizard step, tab draft

⚡ Quick Reference

TaskCode
SavelocalStorage.setItem('key', 'value')
ReadlocalStorage.getItem('key')
Delete onelocalStorage.removeItem('key')
Delete alllocalStorage.clear()
Count keyslocalStorage.length
Store objectsetItem('k', JSON.stringify(obj))

Examples Gallery

Five short examples from basic save/read to a full page with four buttons. Try It Yourself demos use plain HTML with no CSS.

Example 1 — Save and Read a String

js
localStorage.setItem('username', 'JohnDoe');
var name = localStorage.getItem('username');
console.log(name); // JohnDoe
Try It Yourself

How It Works

Reload the Try It page after saving—the name remains until you clear localStorage.

Example 2 — Store an Object with JSON

js
var user = { name: 'Jane', theme: 'dark' };
localStorage.setItem('user', JSON.stringify(user));

var loaded = JSON.parse(localStorage.getItem('user'));
console.log(loaded.theme); // dark
Try It Yourself

How It Works

Wrap JSON.parse in try/catch if stored data might be corrupted.

Example 3 — Remove One Key

js
localStorage.setItem('draft', 'hello');
localStorage.removeItem('draft');
console.log(localStorage.getItem('draft')); // null
Try It Yourself

How It Works

removeItem on a missing key does not throw an error.

Example 4 — List All Keys

js
for (var i = 0; i < localStorage.length; i++) {
  var key = localStorage.key(i);
  console.log(key, localStorage.getItem(key));
}
Try It Yourself

How It Works

Useful for debugging what your app stored. Inspect DevTools → Application → Local Storage too.

Example 5 — Example (Full Page)

Complete demo with save, retrieve, remove, and clear buttons from the reference tutorial:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Local Storage Example</title>
</head>
<body>
  <h1>HTML Local Storage Example</h1>
  <button id="save">Save to Local Storage</button>
  <button id="retrieve">Retrieve from Local Storage</button>
  <button id="remove">Remove from Local Storage</button>
  <button id="clear">Clear All Local Storage</button>
  <p id="output"></p>

  <script>
    document.getElementById('save').onclick = function () {
      localStorage.setItem('greeting', 'Hello, World!');
      document.getElementById('output').textContent = 'Data saved!';
    };
    document.getElementById('retrieve').onclick = function () {
      var greeting = localStorage.getItem('greeting');
      document.getElementById('output').textContent =
        greeting ? greeting : 'No data found';
    };
    document.getElementById('remove').onclick = function () {
      localStorage.removeItem('greeting');
      document.getElementById('output').textContent = 'Data removed!';
    };
    document.getElementById('clear').onclick = function () {
      localStorage.clear();
      document.getElementById('output').textContent = 'All data cleared!';
    };
  </script>
</body>
</html>
Try It Yourself

How It Works

Close the browser and reopen—greeting is still there until you Remove or Clear.

🚀 Common Use Cases

  • Theme mode — dark/light preference across visits.
  • Language or locale — remember UI language choice.
  • Shopping cart — hold items between sessions (not for payment secrets).
  • Form drafts — autosave long comments or blog posts.
  • Onboarding flags — “has seen tutorial” toggle.
  • Cross-tab sync — listen for the storage event when another tab writes.

🧠 How localStorage Works (Step by Step)

1

Page calls setItem

JavaScript writes a string under a key for this origin.

Write
2

Browser persists data

Stored on disk per origin (protocol + host + port).

Save
3

Any tab on same site

All tabs share the same localStorage keys.

Share
4

Later visit: getItem

Page reads saved values on load.

Read
=

Until cleared

Data survives reloads, restarts, and new tabs.

Universal Browser Support

localStorage is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. It is part of the HTML5 Web Storage specification.

Baseline · Since HTML

localStorage API

localStorage is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. It is part of the HTML5 Web Storage specification.

98% Modern browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
localStorage API Excellent

Bottom line: Safe to use in all current projects. Feature-detect with typeof localStorage !== 'undefined' in very old environments.

💡 Best Practices

✅ Do

  • Use localStorage for small, non-sensitive preferences
  • Serialize objects with JSON.stringify / JSON.parse
  • Pick clear key names (theme, cartItems)
  • Remove keys when data is no longer needed
  • Handle null from getItem before using values
  • Use the storage event for cross-tab updates

❌ Don’t

  • Store passwords, tokens, or PCI data
  • Assume unlimited space (stay under ~5 MB)
  • Store huge JSON blobs (use IndexedDB instead)
  • Trust localStorage values without validation
  • Block the main thread with massive synchronous writes
  • Use localStorage when tab-only data is enough (use sessionStorage)

Conclusion

HTML Local Storage is an easy-to-use and efficient way to store data on the client side. It is perfect for saving small amounts of persistent data without relying on external databases or cookies.

However, it’s important to be mindful of its limitations, especially when dealing with sensitive information and large datasets. For tab-scoped data, see Session Storage. For structured offline data, see IndexedDB.

Key Takeaways

Knowledge Unlocked

Five things to remember about localStorage

Use these points when picking client-side storage.

5
Core concepts
🔗 02

Shared tabs

Same origin.

Scope
📝 03

Strings

JSON helps.

Type
📈 04

~5 MB

Per origin.

Limit
🔒 05

Not secure

No secrets.

Safety

❓ Frequently Asked Questions

localStorage is part of the Web Storage API. It stores key-value string pairs in the browser for the current origin. Data persists after the tab or browser is closed until you remove it or the user clears site data.
localStorage is shared across all tabs on the same origin and lasts until cleared. sessionStorage is scoped to one tab and is deleted when that tab closes.
Call localStorage.setItem('key', 'value'). Both key and value must be strings. Retrieve with localStorage.getItem('key'), which returns null if the key does not exist.
Only strings are stored directly. Serialize objects with JSON.stringify(obj) before setItem, and parse with JSON.parse(localStorage.getItem('key')) when reading.
No. Unlike cookies, localStorage data stays in the browser and is not included in HTTP requests. That makes it more efficient for client-only preferences.
Browsers typically allow about 5 MB per origin for localStorage. Storing very large strings may throw a QuotaExceededError.
Did you know?

When one tab changes localStorage, other tabs on the same origin receive a storage event. That is a simple way to sync theme or logout state across tabs without WebSockets.

Practice localStorage in the editor

Save a greeting, close the tab, reload tomorrow—it is still there. Plain HTML, no CSS required.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful