Skip to content

Local Storage

This lesson explains Local Storage with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Local Storage API Overview

The HTML5 Local Storage API provides a simple way to store key-value data directly in the user's browser. Unlike cookies, Local Storage data is not sent to the server with every HTTP request and remains available even after the browser is closed and reopened.

Local Storage is ideal for storing user preferences, themes, language settings, shopping cart information, recently viewed items, draft forms, feature flags, and other small amounts of client-side data.

Feature Description
API Name Local Storage API
Main Object window.localStorage
Storage Type Persistent browser storage
Data Format String key-value pairs
Expiration Never expires until removed
Typical Storage Limit Approximately 5-10 MB depending on browser

Why Use Local Storage?

Before HTML5, developers mainly relied on cookies for client-side storage. Cookies are automatically sent with every HTTP request, increasing network traffic and limiting storage capacity. Local Storage solves these problems by providing larger storage that remains entirely within the browser.

Feature Local Storage Cookies
Storage Size 5-10 MB About 4 KB
Sent to Server No Yes
Expiration Persistent Configurable
Data Type Strings Strings
Performance Better for client-side data Better for sessions

Basic Local Storage Example

// Save data

localStorage.setItem(
  "username",
  "John"
);

// Read data

const username =
  localStorage.getItem(
    "username"
  );

console.log(username);

The browser stores the value using the specified key. The value remains available even after refreshing or reopening the browser.

Local Storage Methods

Method Description Example
setItem() Stores a key-value pair. localStorage.setItem()
getItem() Reads a value by key. localStorage.getItem()
removeItem() Deletes one key. localStorage.removeItem()
clear() Deletes every key. localStorage.clear()
key() Returns a key by index. localStorage.key(0)
length Total stored items. localStorage.length

Store Data

// Store user information

localStorage.setItem(
  "name",
  "Alice"
);

localStorage.setItem(
  "city",
  "Dallas"
);

localStorage.setItem(
  "theme",
  "dark"
);

All values are stored as strings. Numbers and booleans are automatically converted into strings.

Retrieve Data

const theme =
  localStorage.getItem(
    "theme"
  );

console.log(theme);

If the specified key does not exist, getItem() returns null.

Remove One Item

localStorage.removeItem(
  "theme"
);

Only the specified key is removed. All other stored values remain unchanged.

Clear Local Storage

localStorage.clear();

The clear() method removes every key stored by the current website.

Store JavaScript Objects

Local Storage only stores strings. JavaScript objects should be converted to JSON before storing.

const user =
  {
    id: 101,
    name: "Alice",
    role: "Developer"
  };

localStorage.setItem(
  "user",
  JSON.stringify(user)
);

Retrieve JavaScript Objects

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

console.log(user.name);

JSON.parse() converts the stored JSON string back into a JavaScript object.

Store Arrays

const skills =
  [
    "HTML",
    "CSS",
    "JavaScript"
  ];

localStorage.setItem(
  "skills",
  JSON.stringify(skills)
);

const storedSkills =
  JSON.parse(
    localStorage.getItem(
      "skills"
    )
  );

console.log(storedSkills);

Loop Through Local Storage

for (
  let i = 0;
  i < localStorage.length;
  i++
) {

  const key =
    localStorage.key(i);

  console.log(
    key,
    localStorage.getItem(key)
  );

}

The key() method returns the key stored at a specific index.

Real-World Example: Save Theme Preference

const theme =
  localStorage.getItem(
    "theme"
  );

if (theme) {
  document.body.dataset.theme =
    theme;
}

function changeTheme(theme) {
  document.body.dataset.theme =
    theme;

  localStorage.setItem(
    "theme",
    theme
  );
}

Users continue seeing their preferred theme after refreshing or reopening the website.

Real-World Example: Save Form Draft

const textarea =
  document.querySelector(
    "#message"
  );

textarea.value =
  localStorage.getItem(
    "draft"
  ) || "";

textarea.addEventListener(
  "input",
  () => {
    localStorage.setItem(
      "draft",
      textarea.value
    );
  }
);

This technique prevents users from losing typed content after accidentally refreshing the page.

Feature Detection

if (
  "localStorage" in window
) {

  console.log(
    "Local Storage supported."
  );

} else {

  console.log(
    "Local Storage unavailable."
  );

}

Feature detection helps applications gracefully handle older browsers or restricted browsing modes.

Storage Event

window.addEventListener(
  "storage",
  (event) => {

    console.log(
      event.key,
      event.newValue
    );

  }
);

The storage event is triggered in other browser tabs whenever Local Storage changes.

Local Storage Limitations

  • Stores only strings.
  • Cannot directly store JavaScript objects.
  • Synchronous API that can block the main thread.
  • Limited storage capacity.
  • Not suitable for large datasets.
  • Accessible from JavaScript running on the page.

Local Storage vs Session Storage vs IndexedDB

Feature Local Storage Session Storage IndexedDB
Persistence Permanent Current tab only Permanent
Storage Size 5-10 MB 5-10 MB Hundreds of MB
Objects JSON only JSON only Native objects
Async No No Yes
Best Use Preferences Temporary data Offline applications

Common Local Storage Use Cases

  • Dark mode preference.
  • Language selection.
  • Shopping cart items.
  • Remember recently viewed products.
  • Draft forms.
  • User interface settings.
  • Feature flags.
  • Simple application cache.

Local Storage Best Practices

  • Store only small amounts of data.
  • Use JSON for objects and arrays.
  • Always handle missing keys safely.
  • Remove obsolete values.
  • Use feature detection before accessing Local Storage.
  • Use IndexedDB for large structured data.
  • Validate stored values before using them.
  • Keep keys organized with meaningful names.

Common Local Storage Mistakes

  • Storing passwords or authentication tokens.
  • Saving very large datasets.
  • Forgetting to use JSON.stringify().
  • Calling JSON.parse() on invalid data.
  • Assuming values are numbers instead of strings.
  • Ignoring storage limits.
  • Using Local Storage for sensitive information.
  • Not cleaning outdated values.

Key Takeaways

  • Local Storage stores persistent key-value data in the browser.
  • Only strings can be stored directly.
  • Use JSON for objects and arrays.
  • Data remains after browser restarts.
  • Local Storage is ideal for small client-side preferences.
  • Never store sensitive information such as passwords or JWT tokens.

Pro Tip

Use Local Storage for lightweight user preferences like theme, language, and layout settings. For large offline datasets, search indexes, or cached application data, prefer IndexedDB because it is asynchronous, scalable, and designed for structured storage.