Skip to main content

Frontend System Design: Web Storages

URL, cookies, localStorage, sessionStorage, Cache API, IndexedDB or the server: how to pick the right home for every piece of data

Updated 28 min readMarkdown

Every frontend app eventually hits the same question: "Where should this piece of data live?"

The selected theme. A half-written post. The filters on a product list. A login session. A 40 MB video someone wants to watch on a plane. Each of these has a different "right home", and picking the wrong one leads to bugs that are hard to spot: data that vanishes, pages that feel sluggish, or tokens that an attacker can read.

Most of us default to localStorage for everything. This post is about the other options too, and how to choose between them, whether you're building your first app or answering a system design interview.

Credit: this post is based on the video [Frontend System Design] Web Storages by Dmitriy Zhiganov, part of his Frontend System Design series. I've rewritten it in my own words, added examples and diagrams, and updated a few details that have changed in browsers since. Go watch the original. It's excellent.


How to read this post

The main text tells the whole story. Level boxes add depth for those who want it.

Marker Who it's for What you get
๐ŸŸข Beginner New to web development The idea in plain words
๐Ÿ”ต Junior Building your first real projects Code you can copy, and common mistakes
๐ŸŸก Mid Shipping production code Trade-offs, performance, security
๐Ÿ”ด Senior Designing systems, interviewing Quotas, eviction, sync, edge cases

If you're a beginner, read the plain text and skip the ๐ŸŸก and ๐Ÿ”ด boxes on your first pass.


The storages as rooms in a house ๐Ÿ 

Before any code, here is every option we'll cover as a place to keep things in a house:

Storage The house version
JavaScript memory (variables) Things in your hands. Drop them (reload the page) and they're gone.
URL A note written on the front door. Anyone you send the address to can read it.
Cookies An ID badge you automatically show at every door you walk through.
localStorage A whiteboard in your own room. It stays until someone wipes it.
sessionStorage A whiteboard in a hotel room. It's wiped when you check out (close the tab).
Cache API A pantry of ready-made meals (saved server responses).
IndexedDB A warehouse with labelled shelves and an index to find things fast.
Server database A bank vault. Safe, shared, reliable, but you have to travel there.

We'll skip two old or niche options: WebSQL (deprecated and removed from browsers) and the File System APIs (covered briefly in a ๐Ÿ”ด box later).


First, one word you need: "origin"

Most browser storages are locked to an origin. An origin is three things together:

   https://   shop.example.com   :443
   \_____/    \______________/   \__/
   protocol       host name      port  (usually hidden, because it's the default)

Two URLs share an origin only when all three match:

URL A URL B Same origin?
https://example.com https://example.com/app/index.html โœ… The path doesn't matter
https://example.com http://example.com โŒ Different protocol
https://example.com https://shop.example.com โŒ Different host
https://example.com https://example.com:8080 โŒ Different port

๐ŸŸข Why you care: data that https://example.com saves in localStorage or IndexedDB is invisible to https://shop.example.com. If your app moves to a new subdomain, your users' saved data doesn't come with it.

๐Ÿ”ด Senior: cookies play by different rules. They're scoped by domain and path, ignore the port, and can be shared across subdomains with the Domain attribute. Don't assume cookie scoping matches the other storages.


The whole lineup at a glance

Storage Roughly how much How long it lasts Sent to the server automatically? API style Usable in workers? Stores
Memory Your RAM Until reload No Sync Own memory only Anything
URL Keep it under ~2,000 characters As long as the link exists Yes (it's the address) Sync n/a Short text
Cookies ~4 KB per cookie Until it expires Yes, on every request Sync Limited Short text
localStorage ~5 MB Until deleted (or evicted) No Sync โŒ Strings only
sessionStorage ~5 MB Until the tab closes No Sync โŒ Strings only
Cache API Large shared quota (GBs) Until deleted (or evicted) No Async โœ… Request/response pairs
IndexedDB Large shared quota (GBs) Until deleted (or evicted) No Async โœ… Almost any JS value, files
Server database Whatever you pay for As long as you keep it n/a Network โœ… Anything

Keep this table handy. The rest of the post explains each row.


1. The URL: storage you can share ๐Ÿ”—

๐ŸŸข Beginner: You might not think of the URL as storage, but the part after the ? (the query string, or search params) can hold state:

https://shop.example.com/shoes?color=red&size=9&sort=price&page=2
                               \___________________________________/
                                      this is state, stored in the URL

It survives a page refresh. And it has a superpower no other storage has: you can share it. Copy the link, send it to a friend, and they see exactly the same filtered list. Bookmark it, and you come back to the same view.

Good for:

  • Search queries, filters, sorting and page numbers in a table or product list.
  • A configured view of a dashboard or a map (zoom level, selected region).
  • Anything a user might want to send to someone: "Which of these jackets should I buy?"

Not good for:

  • Anything private. URLs end up in browser history, server logs, analytics tools and screenshots.
  • Large or complex data. Keep it short and simple: strings, numbers, true/false.
  • Anything that must not be lost. The user can edit or delete it at any time.

๐Ÿ”ต Junior: reading and writing search params:

// Read the current filters from the URL
const params = new URLSearchParams(location.search);
const page = Number(params.get('page') ?? 1);
const sort = params.get('sort') ?? 'newest';

// Change one value without reloading the page
params.set('page', String(page + 1));
history.replaceState(null, '', `?${params}`);

Use history.pushState instead of replaceState if you want the Back button to step through each change (for example, through pages of results).

๐ŸŸก Mid: modern browsers accept very long URLs, but servers, proxies and CDNs often reject anything much over a few thousand characters. Treat roughly 2,000 characters as the safe ceiling. Frameworks like Next.js and React Router make search params easy to read in components. When the URL holds the state, treat it as the single source of truth, so you don't keep two copies that drift apart.


2. Cookies: the storage that talks to the server ๐Ÿช

Cookies have two features nothing else has:

  1. The server can set them (with a Set-Cookie response header).
  2. The browser sends them back automatically with every request to that site.

That makes cookies brilliant for a few specific jobs, and a poor choice as general storage.

The downsides:

  • Tiny: about 4 KB per cookie, and a limited number per site.
  • Sent with every request. Every image, script and API call to your domain carries all the matching cookies. Big cookies make everything slower.

The upside: cookies can be made invisible to JavaScript with the HttpOnly flag. Even if an attacker manages to inject a script into your page (an XSS attack), they can't read that cookie.

Job 1: Keeping users logged in

 Browser                                      Server
    โ”‚ โ”€โ”€ POST /login (email + password) โ”€โ”€โ”€โ”€โ–ถ โ”‚  checks the credentials
    โ”‚ โ—€โ”€โ”€ 200 OK                               โ”‚
    โ”‚     Set-Cookie: session=abc123; HttpOnly โ”‚
    โ”‚                                          โ”‚
    โ”‚ โ”€โ”€ GET /profile                          โ”‚
    โ”‚    Cookie: session=abc123 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถ โ”‚  "abc123 is a valid session: this is Asha"
    โ”‚ โ—€โ”€โ”€ 200 OK + Asha's profile โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚

Notice that no JavaScript had to attach the token to each request. The browser did it.

๐Ÿ”ต Junior: a good session cookie looks like this:

Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=86400
Flag What it does
HttpOnly JavaScript can't read it (document.cookie won't show it)
Secure Only sent over HTTPS
SameSite=Lax Not sent on most requests started by other sites, which blocks many CSRF attacks
Max-Age How many seconds it lives. Without it, the cookie dies when the browser session ends.

Job 2: Personalizing the very first response

Say a user picks Hindi as their language. If you store that choice in a cookie, the server sees it on the user's next visit and can send back the Hindi page straight away. With localStorage, the server can't see the choice, so you'd send the default language first, then JavaScript would read localStorage, then switch languages, and the page flickers.

 With a cookie:        GET /  (Cookie: lang=hi)  โ”€โ”€โ–ถ  Hindi page        โœ… one round trip
 With localStorage:    GET /  โ”€โ”€โ–ถ  English page  โ”€โ”€โ–ถ  JS reads "hi"  โ”€โ”€โ–ถ  re-render in Hindi  ๐Ÿ”

Job 3: Tracking (the one people complain about)

An ad provider's script runs on site A and site B. The provider's server sets a cookie with a user ID on its own domain. Because that cookie is sent back every time any site loads the provider's ads, the provider can connect "this person visited A, then B". These are third-party cookies.

๐ŸŸก Mid: Safari and Firefox block third-party cookies by default, and Chrome lets users block them. Don't build features that depend on them. Third-party cookies also need SameSite=None; Secure to be sent at all.

๐Ÿ”ด Senior:

  • Serve static assets from a separate, cookie-free domain, or keep cookies scoped with Path so images and scripts don't carry them. On HTTP/2 and HTTP/3 header compression softens the cost, but it isn't zero.
  • The __Host- prefix (__Host-session=...) forces Secure, Path=/ and no Domain, so a subdomain can't overwrite your session cookie.
  • Partitioned cookies (CHIPS) let embedded widgets keep state per top-level site without enabling cross-site tracking.

3. localStorage: the simple default ๐Ÿ“

We finally reach a storage meant for storing data. localStorage is:

  • Persistent: data stays after the tab or browser closes (with caveats, see quotas and eviction).
  • Dead simple: four methods and you're done.
localStorage.setItem('theme', 'dark');
localStorage.getItem('theme');       // "dark"
localStorage.removeItem('theme');
localStorage.clear();                // removes everything for this origin

The downsides:

  • Small: about 5 MB per origin.
  • Synchronous: every read and write blocks the main thread. Read 3 MB of JSON on startup and your page freezes while it happens.
  • Strings only: everything else must be converted.
  • Not available in web workers or service workers, which are exactly where offline features live.
  • Readable by any script on your page, including an attacker's if you have an XSS hole.

๐Ÿ”ต Junior: the "strings only" trap:

localStorage.setItem('count', 5);
localStorage.getItem('count');            // "5"  (a string, not a number)

localStorage.setItem('user', { name: 'Asha' });
localStorage.getItem('user');             // "[object Object]"  ๐Ÿ˜ฌ

// Do this instead
localStorage.setItem('user', JSON.stringify({ name: 'Asha' }));
const user = JSON.parse(localStorage.getItem('user') ?? 'null');

Good for:

  • User preferences: theme, language, "don't show this tip again", collapsed sidebar.
  • Small app data when you can't (or don't want to) use a backend, such as a simple to-do list.
  • Short drafts: a comment or a form someone is filling in.
  • A small queue of actions done offline, to send to the server later.

๐ŸŸก Mid: Is localStorage "bad"? You'll hear that you should always use IndexedDB instead. That's an overreaction. For small, simple data, localStorage is fast enough, easy to reason about, and used by huge production apps. The problem is scale: it doesn't grow with your data. Use it for kilobytes, not megabytes.

๐ŸŸก Mid: Defensive writes. Writes can throw (storage full, or storage blocked by the user or a strict privacy setting). Wrap them:

function save(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
    return true;
  } catch (err) {
    console.warn(`Could not save "${key}"`, err); // e.g. QuotaExceededError
    return false;
  }
}

๐Ÿ”ด Senior: cross-tab sync for free. When one tab changes localStorage, every other tab of the same origin receives a storage event. That's a cheap way to sync a theme change or a logout across tabs:

window.addEventListener('storage', (event) => {
  if (event.key === 'theme') applyTheme(event.newValue);
});

Also, version your keys (settings:v2). When the shape of your data changes, old values from months ago will still be sitting in users' browsers.


4. sessionStorage: localStorage for one tab ๐Ÿ—‚๏ธ

sessionStorage has the same API as localStorage. The difference is how long data lives, and who can see it.

๐ŸŸข Beginner: A "session" starts when you open a page in a tab, and ends when that tab is closed.

 Tab 1: example.com          Tab 2: example.com
 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 โ”‚ sessionStorage A โ”‚        โ”‚ sessionStorage B โ”‚   โ† separate, even on the same origin
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚ reload                    โ”‚ close the tab
         โ–ผ                           โ–ผ
   still there โœ…                 gone ๐Ÿ—‘๏ธ
  • Survives reloads (and usually "reopen closed tab").
  • Not shared between tabs, even tabs on the same site.
  • Duplicating a tab copies its sessionStorage into the new tab. After that, the two copies change independently.
  • Cleans itself up when the tab closes. No stale data to delete.

It inherits localStorage's downsides: small, synchronous, strings only.

Good for:

  • Multi-step flows, like a checkout wizard or a long signup form. If the user reloads on step 3, they don't lose steps 1 and 2.
  • Per-tab state: two tabs editing two different things shouldn't overwrite each other.
  • A short-lived cache: data fetched once and reused while the tab is open.
  • App-wide settings for this visit, without leaking into the next one.

๐Ÿ”ต Junior:

// Step 1 of a checkout wizard
sessionStorage.setItem('checkout', JSON.stringify({ step: 1, address }));

// Later, on step 3 (even after a reload)
const checkout = JSON.parse(sessionStorage.getItem('checkout') ?? '{}');

๐ŸŸก Mid: a classic bug is putting per-tab state in localStorage. The user opens two tabs, picks different options in each, and the last tab to save wins for both. If the state belongs to this tab, use sessionStorage.


5. Cache API: a pantry of server responses ๐Ÿฅซ

The Cache API stores request โ†’ response pairs: "when someone asks for /index.html, here's the response I saved." It's not general-purpose storage like localStorage. It's built for keeping copies of things the server sent you.

Its key feature: it works inside service workers, the scripts that sit between your page and the network. Together they let your app load without a connection.

 First visit:
   Page โ”€โ”€GET /index.htmlโ”€โ”€โ–ถ Service worker โ”€โ”€"not in cache"โ”€โ”€โ–ถ Network โ”€โ”€โ–ถ Server
                                    โ”‚โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ response โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                    โ”œโ”€โ”€ saves a copy in the Cache API ๐Ÿ“ฆ
   Page โ—€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ response โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

 Next visit (even offline):
   Page โ”€โ”€GET /index.htmlโ”€โ”€โ–ถ Service worker โ”€โ”€"found it!" ๐Ÿ“ฆโ”€โ”€โ–ถ Page   (no network needed)

๐Ÿ”ต Junior: a minimal "cache first" service worker:

// sw.js
self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;   // only GET responses can be cached

  event.respondWith((async () => {
    const cache = await caches.open('pages-v1');
    const cached = await cache.match(event.request);
    if (cached) return cached;                    // โ‘  found it: no network needed

    const response = await fetch(event.request);  // โ‘ก not found: go to the network
    cache.put(event.request, response.clone());   // โ‘ข keep a copy for next time
    return response;
  })());
});

Good for:

  • Offline support: cache your HTML, CSS, JavaScript and icons so the app opens without a connection.
  • Faster repeat loads, even if you don't care about offline. Reading from disk beats a round trip to the server.

A real-world example from the video: Slack uses service workers with the Cache API (and IndexedDB for data) so the app starts quickly on repeat visits and still works when the connection drops.

Cache API vs. the browser's own HTTP cache

These are easy to confuse. They're two different things:

Browser HTTP cache Cache API
Who controls it The browser, following Cache-Control headers You, in code
Can you read or write it directly? No Yes
Depends on Cache-Control? Yes No
Main purpose Fewer network requests Offline support, full control

๐ŸŸก Mid: with the HTTP cache, a file marked Cache-Control: max-age=... is reused from disk without asking the server. A file marked no-cache is checked with the server every time. If it hasn't changed, the server (or CDN) replies 304 Not Modified with no body, and the browser uses its saved copy. That costs one round trip but means you never show stale files. (I go deeper on this in How a Browser Loads a Website.)

๐Ÿ”ด Senior: name your caches with a version (pages-v1, pages-v2) and delete old ones in the service worker's activate event. Otherwise every deploy leaves another copy of your app on users' disks. And pick a strategy per resource type: cache-first for hashed static assets, network-first for HTML, stale-while-revalidate for things like avatars.


6. IndexedDB: a real database in the browser ๐Ÿ—„๏ธ

IndexedDB is a NoSQL database built into every modern browser. It's the heavy-duty option:

  • Big: it uses the origin's large shared quota, often gigabytes.
  • Asynchronous: reads and writes don't block the main thread.
  • Stores almost any JavaScript value: objects, arrays, dates, Maps, and binary data like Blobs and files. (Not functions.)
  • Powerful: indexes for fast lookups, transactions so a group of changes all succeed or all fail, and versioned schemas.
  • Works in web workers and service workers.

The catch is the API. It's old, event-based and verbose:

// Raw IndexedDB: saving one object
const request = indexedDB.open('my-app', 1);
request.onupgradeneeded = () => {
  request.result.createObjectStore('drafts', { keyPath: 'id' });
};
request.onsuccess = () => {
  const tx = request.result.transaction('drafts', 'readwrite');
  tx.objectStore('drafts').put({ id: 'draft-42', title: 'My trip to Goa' });
  tx.oncomplete = () => console.log('Saved');
  tx.onerror = () => console.error(tx.error);
};

๐Ÿ”ต Junior: almost nobody writes that by hand. Use a small wrapper library like idb, which gives you promises and async/await:

import { openDB } from 'idb';

const db = await openDB('my-app', 1, {
  upgrade(db) {
    const drafts = db.createObjectStore('drafts', { keyPath: 'id' });
    drafts.createIndex('byUpdatedAt', 'updatedAt');
  },
});

await db.put('drafts', {
  id: 'draft-42',
  title: 'My trip to Goa',
  body: 'It all started with a missed train...',
  cover: imageBlob,          // binary files are fine
  updatedAt: Date.now(),
});

const draft = await db.get('drafts', 'draft-42');
const allByDate = await db.getAllFromIndex('drafts', 'byUpdatedAt'); // oldest first

(Dexie is another popular option if you want a query-builder style.)

Good for:

  • Lots of data on the client: thousands of messages, a product catalog, a big search index.
  • Complex structures: a post with a title, body, tags and attachments.
  • Binary files: images, audio or video for offline use, or files waiting to be uploaded.
  • Offline-first apps that must work just as well with no connection, or apps with no backend at all.

๐Ÿ”ด Senior: the File System option. The video skips the File System APIs, and for most apps that's still right. One part of them is worth knowing: the Origin Private File System (OPFS) is now supported in all major browsers. It gives each origin a private, fast file system and is what powers running SQLite in the browser via WebAssembly. Reach for it if you need a real SQL database client-side.


7. A problem every client storage shares โš ๏ธ

Before trusting any browser storage with important data, know these limits. They hit IndexedDB hardest, because that's where people put data they expect to keep.

1. Safari may delete your data after 7 days. Safari's tracking prevention can wipe all script-written storage for a site (localStorage, IndexedDB, Cache API, service workers) if the user hasn't interacted with that site in 7 days of using Safari. Web apps added to the home screen are treated differently. The lesson: in Safari, browser storage is a cache, not a vault.

2. Private browsing is temporary. In private or incognito windows, storage works but is thrown away when the window closes. Older versions of Firefox didn't support IndexedDB in private windows at all. There's no reliable API to detect private mode, so if storage matters, try opening the database and show a helpful message if it fails.

3. Quotas differ between browsers. How much you can store, and what happens when you run out, varies. That's the next section.


8. Quotas and eviction: why "persistent" isn't forever ๐Ÿงฎ

๐ŸŸข Beginner: a quota is how much disk space the browser lets your site use. Eviction is the browser deleting your site's data to free up space.

๐ŸŸก Mid: who shares what.

 Your origin's big shared quota
 โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
 โ”‚  IndexedDB  +  Cache API  +  OPFS  + ...      โ”‚   โ† one bucket. If IndexedDB fills it,
 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     the Cache API can't write either.

 Separate, small, fixed limits
   localStorage โ‰ˆ 5 MB     sessionStorage โ‰ˆ 5 MB     cookies โ‰ˆ 4 KB each
   Browser HTTP cache: managed by the browser, not your problem

Roughly how big that shared bucket is (these change between browser versions, so check MDN's "Storage quotas and eviction criteria" page for current numbers):

Browser Shared quota per origin (approximate)
Chrome / Edge Up to ~60% of total disk space
Firefox ~10% of disk or 10 GB, whichever is smaller, shared by a site and its subdomains
Safari (17+) Up to ~60% in the Safari app, less in apps that embed web views

You don't have to guess. Ask the browser:

const { usage, quota } = await navigator.storage.estimate();
console.log(`Using ${(usage / 1e6).toFixed(1)} MB of ~${(quota / 1e6).toFixed(0)} MB`);

๐Ÿ”ด Senior: best-effort vs. persistent.

Mode When the disk fills up
Best-effort (the default) The browser may silently delete whole origins' data, least recently used first
Persistent The browser won't evict your data automatically. Writes fail with QuotaExceededError instead, so you must catch them.

You can ask for persistent mode:

if (!(await navigator.storage.persisted())) {
  const granted = await navigator.storage.persist();
  console.log(granted ? 'Protected from eviction' : 'Still best-effort');
}

Firefox asks the user. Chrome and Safari decide automatically based on how the user engages with your site (for example, bookmarking it or installing it as an app). You need this for offline-first apps where losing local data means losing user work.


9. When to move data to the server ๐Ÿฆ

Sometimes the best client storage is none. A server-side database has three things no browser storage can match:

  • Reliability: no 7-day wipes, no eviction, no "cleared my browser data."
  • Security: sensitive data never sits where an injected script can read it.
  • Sharing: the same data on a phone, a laptop, and for other users.

Put it on the server when the data is:

  • Sensitive: personal details, payment info, anything you'd hate to see leaked.
  • Needed on other devices: "start on my laptop, finish on my phone."
  • Important: if losing it would make a user angry, it doesn't belong only in the browser.

๐ŸŸก Mid: so why not put everything on the server?

  • Cost: storage, request handling and scaling all cost money, and grow with every user.
  • Speed: every read and write is a network round trip. On a slow connection, the UI feels it.
  • Offline: without a connection, the app gets much worse, or stops working.

That's why real apps combine both: the server holds the truth, and the browser holds fast, temporary copies.

Storage vs. state managers

๐Ÿ”ต Junior: Redux, Zustand, MobX, Pinia and TanStack Query are not storages. They're managers: they organize data in JavaScript memory, give you a clean API to read and update it, and notify components when it changes. Reload the page and that memory is gone.

To keep state across reloads, they write to a real storage through a plugin. For example, Zustand's persist middleware saves to localStorage by default, and TanStack Query has persisters that can write to IndexedDB. So the same rules apply: if a persisted store gets big, localStorage's 5 MB limit and synchronous API become your problem.


10. How to choose: a decision guide ๐Ÿงญ

Walk down this list and stop at the first "yes":

 "Where should this data live?"
  โ”‚
  โ”œโ”€ Is it secret? (passwords, tokens, personal data) โ”€โ”€โ”€โ”€โ”€ yes โ”€โ–ถ Server DB
  โ”‚                                                                  (login session โ†’ HttpOnly cookie)
  โ”œโ”€ Must the server see it on every request? โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ yes โ”€โ–ถ Cookie (keep it tiny)
  โ”œโ”€ Should it survive being shared as a link/bookmark? โ”€โ”€ yes โ”€โ–ถ URL search params
  โ”œโ”€ Is it an HTTP response? (HTML, JS, CSS, API JSON) โ”€โ”€โ”€ yes โ”€โ–ถ Cache API (+ HTTP cache)
  โ”œโ”€ Is it important, or needed on other devices? โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ yes โ”€โ–ถ Server DB (+ IndexedDB offline)
  โ”œโ”€ Only needed in this tab, for now? โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ yes โ”€โ–ถ sessionStorage
  โ”œโ”€ Large, structured, binary, or used offline? โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ yes โ”€โ–ถ IndexedDB
  โ””โ”€ Small and simple? (theme, language, a short draft) โ”€ yes โ”€โ–ถ localStorage

It's a guide, not a law. Always start from what the feature actually needs.


11. Interview walkthrough: design storage for a social network ๐ŸŽค

"Design Facebook" is a classic frontend system design question. Pretend you've never seen it, and decide where each piece of data lives.

The quick wins

Data Where Why
Login session HttpOnly cookie Sent automatically, unreadable by injected scripts
Search query, filters, sort order URL Short-lived, not sensitive, and people share and bookmark searches
Theme and language localStorage (plus a cookie if the server renders pages) Small and simple. The cookie lets the server send the right language on the first load.
A half-finished "create a group" wizard sessionStorage Survives a reload, belongs to this tab, cleans itself up
App shell (HTML, JS, CSS, icons) Cache API + HTTP cache Fast repeat loads, works offline
Recently viewed feed, for offline reading IndexedDB Lots of structured data, used offline
Profile, friends, posts Server DB Important, shared, the source of truth

The interesting one: post drafts

Writing a post can take a while. Users want to save a draft and come back. There are three candidates:

Option Pros Cons
localStorage Easiest, no backend work 5 MB, sync API, strings only, no attachments, one device only
IndexedDB Handles big drafts and attachments, async More complex, one device only, can still be wiped
Server DB Reliable, works across devices Needs backend work, needs a connection

What should you pick? It depends on the requirements, and saying that out loud is what interviewers want to hear:

  • If drafts are short and usually finished in one sitting on one device, localStorage ships fastest and needs no backend team.
  • If you need reliability and "start on my phone, finish on my laptop", you need the server.

A strong answer combines them: the server database is the primary store, and IndexedDB is the offline backup.

 Online:         Editor โ”€โ”€saveโ”€โ”€โ–ถ API โ”€โ”€โ–ถ Database โœ…

 Offline:        Editor โ”€โ”€saveโ”€โ”€โ–ถ IndexedDB (pending changes) ๐Ÿ“ฆ

 Back online:    IndexedDB โ”€โ”€syncโ”€โ”€โ–ถ API โ”€โ”€โ–ถ Database โœ… โ”€โ”€โ–ถ clear the pending changes

Why not localStorage here? Posts can be long, and they can have attachments. A synchronous API reading and writing large drafts slows the UI, and localStorage can't hold binary files.

Why not IndexedDB alone? It can't share drafts between devices, and Safari's 7-day rule, eviction or "clear browsing data" can still wipe it.

๐Ÿ”ด Senior: questions to raise before the interviewer does:

  • Conflicts: the user edited the same draft on two devices while offline. Last write wins? Compare updatedAt timestamps or version numbers? Show both and let the user pick?
  • Duplicates: generate the draft ID on the client (crypto.randomUUID()) so retrying a sync never creates two copies.
  • When to sync: the Background Sync API only exists in Chromium browsers, so also sync on the online event and when the app starts.
  • Storage pressure: request persistent storage if offline drafts matter, and handle QuotaExceededError with a clear message.

Common mistakes to avoid ๐Ÿšซ

Mistake Why it hurts Do this instead
Storing auth tokens in localStorage Any injected script can read and steal them HttpOnly, Secure, SameSite cookie
Putting large JSON in localStorage Sync reads freeze the page; 5 MB ceiling IndexedDB
JSON.parse without a fallback A missing or corrupted value crashes your app JSON.parse(value ?? 'null') inside a try
Treating browser storage as permanent Eviction, Safari's 7-day rule, users clearing data Keep important data on the server
Per-tab state in localStorage Two tabs overwrite each other sessionStorage
Big or numerous cookies Sent with every single request Keep cookies tiny; store data elsewhere
Private data in the URL Ends up in history, logs and screenshots Keep URLs for shareable, non-sensitive state
Ignoring write errors Quota errors fail silently and data is lost try/catch every write, tell the user

Cheat sheet ๐Ÿ“‹

Storage Best for Key strength Key weakness
URL Page state: filters, search, pagination Shareable and bookmarkable Small, public, easy to lose
Cookies Sessions, server-side personalization Sent to the server automatically; can be hidden from JS Tiny; adds weight to every request
localStorage Small, long-lived preferences Dead simple Small, sync, strings only
sessionStorage Per-tab and per-visit state Cleans itself up Same limits as localStorage
Cache API Offline assets, faster repeat loads Full control, works in service workers Only for request/response pairs
IndexedDB Large, structured, binary, offline data Big, fast, async, powerful Harder to use (use idb)
Server DB Important, sensitive, shared data Reliable and secure Cost, latency, needs a connection

Wrapping up

There's no "best" storage, only the right one for a particular piece of data. Ask four questions:

  1. How long does it need to live? (This reload, this tab, forever?)
  2. How important is it? (Annoying to lose, or a disaster?)
  3. Who needs to see it? (This tab, the server, other devices, other people?)
  4. How big and how complex is it?

Answer those and the choice usually makes itself. And when you're in an interview, saying why you picked a storage, and what you'd trade off, matters more than the pick itself.


Keep learning

If this helped, share it with a friend preparing for a frontend interview. ๐Ÿ™‚

About the author

No comments yet. Be the first to comment.