Compile Ready
Module 12 · Browser APIs

localStorage

Beginner10m read6m practice16m total
StoragelocalStorageJSONSecurity

Introduction

localStorage is a browser key-value store scoped to an origin. It stores strings, persists across reloads and browser restarts, and is useful for non-sensitive client preferences such as theme, dismissed banners, and lightweight drafts.

It is simple, but interviewers expect you to know its limits: synchronous API, string-only values, quota errors, and serious security implications if XSS is present.

Why This Matters

Candidates often say localStorage is good for tokens because it persists. Senior engineers ask what happens if an attacker runs JavaScript on the page. Since scripts can read localStorage, XSS turns persistence into exposure.

Theory

Core behavior

localStorage stores key-value pairs as strings. Data is scoped by origin: scheme, host, and port. A value set by https://app.example.com is not shared with https://admin.example.com or http://app.example.com.

Common operations are setItem, getItem, removeItem, clear, key, and length. getItem returns a string or null.

JSON serialization

Objects and arrays must be serialized with JSON.stringify and parsed with JSON.parse. Always handle parse errors because users, browser tools, old app versions, or extensions can leave unexpected values.

Synchronous and quota-limited

localStorage is synchronous. Large reads or writes block the main thread, so do not use it for large datasets. Capacity varies by browser but is commonly around a few megabytes per origin. Writes can throw when quota is exceeded or storage is disabled.

Storage comparison

FeaturelocalStoragesessionStorageCookies
CapacityUsually megabytesUsually megabytesAround 4 KB per cookie
ExpiryUntil explicitly clearedUntil tab/session endsExpiry or session based
ScopeOriginOrigin plus tab contextDomain/path rules
Sent to serverNoNoYes, on matching requests
API styleSynchronous string storeSynchronous string storeHeader/document string API

Security notes

Do not store highly sensitive secrets in localStorage. Any successful XSS can read it. Prefer server-managed HttpOnly, Secure, SameSite cookies for session identifiers when the architecture supports them. Client storage can be edited by the user, so it is never an authority for permissions or pricing.

Visual Diagrams

localStorage lifecycle
User sets preference
  |
  v
String saved for origin
  |
  v
Page reload
  |
  v
Preference still available
  |
  v
Explicit remove, clear, or browser data deletion

Persistence is the main feature: data survives page reloads and typical browser restarts.

Origin boundary
https://app.example.com
  has its own localStorage

https://admin.example.com
  separate storage

http://app.example.com
  separate storage because scheme differs

Storage is isolated by scheme, host, and port.

Code Examples

Store and read a simple preference

All values are strings. Use explicit namespacing for keys in larger apps.

Loading…

Store objects with JSON and defensive parsing

Wrap parsing because stored data may be missing, corrupted, or from an older app version.

Loading…

Handle quota or privacy-mode failures

Writes can throw, so production code should fail gracefully.

Loading…

Coding Exercises

Create a safe JSON parser for stored settings

Easy

Implement parseStoredSettings(raw, fallback). If raw is missing or invalid JSON, return fallback. If it parses to an object, merge it over fallback.

Interview Questions

1What can `localStorage` store, and how do you store objects?

localStorage stores strings only. Store objects by calling JSON.stringify before setItem and JSON.parse after getItem. Defensive code handles null, parse errors, and schema changes.

Asked at:MicrosoftAmazonGoogle
2Should authentication tokens be stored in `localStorage`?

Usually avoid it for highly sensitive tokens because any successful XSS can read localStorage. Many session architectures prefer server-set HttpOnly, Secure, SameSite cookies so JavaScript cannot read the session identifier.

Asked at:MetaNetflix

Follow-ups

  • What does `HttpOnly` protect against?
  • What does `SameSite` protect against?

Quiz

1. What does `localStorage.getItem('missing')` return for a missing key?

2. Which statement about `localStorage` is true?

Summary

  • `localStorage` is origin-scoped, persistent, synchronous, and string-only.
  • Use JSON serialization for objects and handle parse/write failures.
  • Do not trust client storage for authorization or sensitive secrets.
  • Unlike cookies, `localStorage` is not automatically sent to the server.

Cheat Sheet

Write: localStorage.setItem(key, stringValue).

Read: localStorage.getItem(key) returns string or null.

Delete: removeItem(key) or clear().

Objects: JSON.stringify on write, JSON.parse on read.

Scope: origin.

Security: readable by JavaScript; XSS can exfiltrate it.

Performance: synchronous; keep values small.