Skip to main content

Data that survives a page reload

By default, JavaScript data disappears when you close or refresh the page. localStorage lets you store data in the browser that persists across page loads, tab closes, and even browser restarts.

The four methods

That’s the entire API. Four methods, all synchronous, all straightforward.

localStorage only stores strings

This is the most important thing to know. localStorage values are always strings.

Storing objects and arrays

Since localStorage only stores strings, you need JSON.stringify() and JSON.parse():
If you forget JSON.stringify() when saving an object, you’ll store the useless string "[object Object]". Always stringify objects before saving and parse after loading.

Safe loading with a fallback

localStorage.getItem() returns null if the key doesn’t exist. Handle this:
If the stored value is invalid JSON (for example, someone manually edited it in DevTools), JSON.parse() will throw. Use try/catch if the data might be corrupted.
Always provide a fallback when loading from localStorage. The data might not exist yet (first visit), or the user might have cleared their browser data.

Practical use cases

Saving user preferences

Saving form drafts

Simple shopping cart

localStorage vs other storage

sessionStorage works exactly like localStorage but data is cleared when the browser tab closes. Use it for truly temporary data like “which tab is selected” or “scroll position.”

When NOT to use localStorage

  • Sensitive data — never store passwords, tokens, or personal data. localStorage is readable by any JavaScript on the page (including malicious scripts).
  • Large data — the ~5-10 MB limit makes it unsuitable for images, videos, or large datasets.
  • Data that must sync across devices — localStorage is per-browser, per-device. Use your backend database for data that should follow the user.
  • Critical application data — users can clear localStorage at any time. Don’t store anything your app can’t recreate from the backend.
Never store authentication tokens in localStorage. It’s vulnerable to XSS attacks — any JavaScript on the page can read it. Use HTTP-only cookies for auth tokens instead.

Inspecting localStorage in DevTools

Open DevTools → Application tab → Local Storage (in the sidebar). You can:
  • View all stored key-value pairs
  • Edit values directly
  • Delete individual keys or clear everything
  • Watch values change in real time

What’s next?

You’ve covered the DOM and browser APIs — selecting elements, modifying the page, handling events, working with forms, and persisting data. These are the building blocks that every framework builds on. Next up: React. You’ll see how React takes everything you’ve learned — DOM manipulation, event handling, state management — and wraps it in a component-based architecture that scales to real applications.

What is React?

Understand why React exists and what problems it solves