Courses / Frontend System Design, with JavaScript Foundations / Chapter 10
Module 4 · Requirements and Fundamentals · Chapter 10 of 21
Frontend Fundamentals: Components, State, Data and Rendering
Builds on Promises, Async Code and the Browser Event Loop, The DOM, Events and Observers, How the Browser Loads and Renders a Page and Non-functional Requirements. Next up: Performance and Optimisation.
Part 1 · Anatomy of a client app
The layers
A web app in the browser is more than components on a screen: its code settles into layers, and knowing them lets you place any new feature quickly. A design question about a feed or a chat starts from the same set of parts.
The view is the components that draw the screen and send user actions upward. The state store holds the data the views read: what is selected, what is in the cart, which request is pending. The data layer knows how to get data: which endpoint to call, how to turn the response into the shapes the app uses, and when to reuse something it already has. The cache remembers earlier answers. The transport is the code that actually speaks HTTP, WebSocket or another protocol. An optional service worker sits between the page and the network and can answer requests itself.
| Layer | It owns | It must not know about |
|---|---|---|
| View | markup, styles, user events | URLs of the API, how data is fetched |
| State store | current app state, change notifications | how a component draws it |
| Data layer | which request to make, mapping responses, retries | markup and styles |
| Cache | remembered responses and when they expire | what the data means |
| Transport | headers, encoding, connections, errors on the wire | what the app is for |
| Service worker | offline answers and request interception | the views |
One request through the layers
The script below builds one tiny version of each layer and logs where a request goes. The transport returns a fixed product in place of a real fetch, which keeps the focus on who calls whom. The view asks for the same product twice.
// transport: the only code that knows about HTTP const transport = { async get(path) { log('transport', `GET ${path}`) // stands in for fetch return { id: 7, name: 'Table butter', paise: 5400 } }, } // cache: remembers answers by key const cache = new Map() // data layer: decides cache or network const data = { async product(id) { const key = `product:${id}` if (cache.has(key)) { log('data', `cache hit ${key}`) return cache.get(key) } log('data', `cache miss ${key}`) const value = await transport.get(`/api/products/${id}`) cache.set(key, value) return value }, }
f1.mjs: transport, cache and data layer. log(layer, text) prints one line.
// store: the state views read const store = { state: { product: null }, async load(id) { log('store', `load product ${id}`) this.state.product = await data.product(id) }, } // view: turns state into what the user sees const view = ({ product: p }) => `${p.name}: ₹${p.paise / 100}` for (const visit of [1, 2]) { log('view', `visit ${visit}: ask for product 7`) await store.load(7) log('view', `shows "${view(store.state)}"`) }
f1.mjs: store and view, and the two visits.
view visit 1: ask for product 7 store load product 7 data cache miss product:7 transport GET /api/products/7 view shows "Table butter: ₹54" view visit 2: ask for product 7 store load product 7 data cache hit product:7 view shows "Table butter: ₹54"
Output (Node 24)
On the first visit the data layer finds nothing in the cache, so the request reaches the transport. On the second visit the data layer answers from the cache and the transport is never called. The view did not change between the two visits, and it does not know which path was taken.
Watch for the second visit: the data layer answers without the network
Read it as steps
Part 2 · Components as contracts
Inputs, outputs and slots
A component is a piece of UI with a defined edge. Whatever framework builds it, the edge has the same parts, and a component is easy to reuse when that edge is small and clear.
Inputs are the values the parent hands in: props or attributes. Outputs are the events the component raises when something happens, such as a rating being chosen. Slots are places where the parent can place its own content inside the component, such as a label. Everything else is internal, and the parent should not reach in to change it.
| Part of the contract | In a web component | Example |
|---|---|---|
| Inputs | attributes and properties | value="3" |
| Outputs | custom events | rating-change |
| Slots | <slot> elements | the label above the stars |
| Internals | a shadow root | the five buttons and their styles |
Written this way, the contract is the same in React, Vue, Angular or a plain browser. This course does not use a framework, so it shows the idea with web components, a set of standards built into the browser. A custom element is a tag you define yourself, such as star-rating, and a shadow root is a private DOM tree attached to it.
A good contract keeps inputs few and data-shaped, names events after what happened rather than what to do, and lets the parent own the state. A rating control that stores its own value silently is hard to use in a form. One that takes value in and announces rating-change out can be driven from a store, from the URL, or from a test.
A custom element
The element below shows a rating. It takes value as an input, raises rating-change as an output, accepts a label in a slot, and keeps its buttons inside a shadow root. The page around it deliberately styles every button red and 40 pixels tall.
<!doctype html><html lang="en"><style> button { color: red; font-size: 40px } /* must not leak in */ </style> <star-rating value="3"> <span slot="label">Rate this butter</span> </star-rating>
f2.html: the page around the element.
<script>
class StarRating extends HTMLElement {
static observedAttributes = ['value']
#root = this.attachShadow({ mode: 'open' })
constructor() {
super()
this.#root.innerHTML = `
<style>button { color: gold } </style>
<slot name="label"></slot>
${[1, 2, 3, 4, 5].map((n) =>
`<button data-n="${n}" aria-label="${n} stars">*</button>`
).join('')}`
this.#root.addEventListener('click', (e) => {
const n = e.target.dataset?.n
if (n) this.setAttribute('value', n)
})
}
attributeChangedCallback(name, oldValue, newValue) {
window.log?.(`${name}: ${oldValue} -> ${newValue}`)
for (const b of this.#root.querySelectorAll('button')) {
b.setAttribute('aria-pressed', String(b.dataset.n <= newValue))
}
this.dispatchEvent(new CustomEvent('rating-change', {
detail: { value: Number(newValue) },
bubbles: true, composed: true,
}))
}
}
customElements.define('star-rating', StarRating)
</script>f2.html: the element.
A Playwright script loads the page, clicks the fifth star with a real click, and then asks Chrome what is visible from outside and what is not.
await page.click('star-rating >> role=button[name="5 stars"]') const facts = await page.evaluate(() => { const el = document.querySelector('star-rating') const inner = el.shadowRoot.querySelector('button') return { outerQuery: document.querySelector('star-rating button'), innerQuery: !!inner, innerColor: getComputedStyle(inner).color, innerSize: getComputedStyle(inner).fontSize, slotted: el.shadowRoot.querySelector('slot') .assignedNodes()[0].textContent, pressed: [...el.shadowRoot.querySelectorAll('button')] .filter((b) => b.getAttribute('aria-pressed') === 'true').length, } }) console.log(lines.join('\n')) for (const [key, value] of Object.entries(facts)) { console.log(`${key}: ${value}`) } await browser.close()
f2.mjs: click, then inspect.
value: null -> 3 value: 3 -> 5 rating-change heard at document: 5 outerQuery: null innerQuery: true innerColor: rgb(255, 215, 0) innerSize: 13.3333px slotted: Rate this butter pressed: 5
Output (Chrome 157)
Lifecycle and what to keep outside
A custom element has lifecycle callbacks that the browser calls at fixed moments. The constructor runs when the element is created or upgraded, and it is the place to build the shadow root, not to read attributes. connectedCallback runs each time the element is added to the document and disconnectedCallback each time it is removed. attributeChangedCallback runs when an attribute listed in static observedAttributes is added, changed or removed, and also once for an observed attribute that is already in the markup. A custom element name must contain a hyphen so it cannot clash with a standard tag.
| Callback | When it runs | Typical use |
|---|---|---|
| constructor | created or upgraded | attach the shadow root |
| connectedCallback | added to the page | start listeners, fetch data |
| disconnectedCallback | removed from the page | stop listeners and timers |
| attributeChangedCallback | an observed attribute changes | update the view |
The disconnected callback is where leaks are prevented. A component that starts a timer or adds a listener to window when it connects must remove it when it disconnects, or it keeps running after its element has gone.
Shadow DOM is optional. Without it a component's markup is part of the page and its styles apply to it, which suits content that should inherit the site's typography. With it you gain isolation and give up easy global theming, so design tokens such as colours are usually passed in with CSS custom properties, which do cross the shadow boundary. Accessibility still applies inside: the buttons here have aria-label and aria-pressed so a screen reader gets a name and a state.
Part 3 · Kinds of state
Five places state can live
Every piece of data in a client app lives somewhere, and most bugs come from the same piece living in two places. A useful habit is to decide, for each piece of state, which of five homes it belongs in.
| Kind | What it holds | Where it lives | Survives a reload |
|---|---|---|---|
| Local UI state | a menu is open, a tab is selected | inside one component | no |
| Shared client state | the cart, the signed-in user, a theme | a store used by many components | only if saved |
| Server cache | products, orders, messages | a cache of server responses | only if persisted |
| URL state | the search text, sort order, page number, selected item | the address bar | yes, and shareable |
| Form state | what the user has typed and not yet saved | the form, until submitted | usually no |
What it holdsa menu is open, a tab is selected
Where it livesinside one component
Survives a reload
A small observable store
A store holds shared state and tells subscribers when it changes. The version below is about twenty-five lines: getState reads, setState merges a patch and notifies, and subscribe registers a listener and returns a function that removes it. A helper called select lets a subscriber hear only about the slice it cares about.
// A small observable store, and state that lives in the URL. const createStore = (initial) => { let state = initial const listeners = new Set() return { getState: () => state, setState(patch) { state = { ...state, ...patch } for (const fn of [...listeners]) fn(state) }, subscribe(fn) { listeners.add(fn) return () => listeners.delete(fn) }, } } const select = (store, pick, onChange) => { let last = pick(store.getState()) return store.subscribe((s) => { const next = pick(s) if (next !== last) { last = next; onChange(next) } }) }
f3.mjs: the store and a selector.
const store = createStore({ items: 0, coupon: '' }) select(store, (s) => s.items, (n) => console.log('badge shows', n)) const stop = store.subscribe((s) => { console.log('any change:', JSON.stringify(s)) }) store.setState({ items: 1 }) store.setState({ coupon: 'FEST10' }) // badge stays quiet stop() store.setState({ items: 2 }) // only the badge hears this // filters belong in the URL so a link or reload restores them const url = new URL('https://shop.example/search?q=butter&sort=price') const filters = Object.fromEntries(url.searchParams) console.log('read from URL:', JSON.stringify(filters)) url.searchParams.set('sort', 'rating') console.log('after a change:', url.search)
f3.mjs: using it, then URL state.
badge shows 1 any change: {"items":1,"coupon":""} any change: {"items":1,"coupon":"FEST10"} badge shows 2 read from URL: {"q":"butter","sort":"price"} after a change: ?q=butter&sort=rating
Output (Node 24)
The badge, which subscribes to items, is told about the first change and the third, and stays quiet when only the coupon changes. The general subscriber hears the first two changes and then unsubscribes, so the third change reaches only the badge. Selecting a slice is what stops every component from redrawing on every change.
The last lines read filters out of a URL with URLSearchParams and write a changed filter back. The view then renders from the URL as its single source for those values, and links and reloads work without extra code.
Choosing a home
A short list of questions settles most placements. Start with the smallest scope that works and move state up only when a second place needs it.
- Does only one component care? Keep it local. A dropdown's open flag never belongs in a global store.
- Should it survive a reload or be shared by link? Put it in the URL.
- Does it come from the server? Put it in the cache from the next lesson, and refresh it there. Do not copy it into a store you also edit.
- Do several distant components read and change it, like the cart? Use a shared store.
- Is it a draft that is not yet valid? Keep it in the form until submit, then send it to the server.
State also differs in how long it must last. The cart may need to survive a closed tab, so it is saved to storage, which the last lesson covers. A selected tab need not. Persisting everything makes stale data last forever, so persist the things whose loss would annoy a user.
Finally, write down who is allowed to change each piece. A store with one function per allowed change, such as addItem and applyCoupon, is easier to reason about than one anything can patch. In the lessons that follow, the data layer owns the server cache, a store owns shared client state, the URL owns navigation state, and components own what is purely visual.
In the run above, why did the badge hear about the first and third changes but not the second?
selectcompares the picked slice with the last one, and onlyitemschanged in the first and third.- The second change only touched
coupon.
A product list can be sorted by price or by rating. Where should the sort choice live and why?
- In the URL, so a reload keeps it and a link shares it.
- Back also undoes the choice.
Part 4 · Fetching and caching on the client
What a data layer must handle
Fetching data looks like one line, fetch(url), until a real screen makes the same call from three components, the user leaves while it is in flight, and the network fails. A data layer exists to handle those cases once.
| Problem | What happens without handling | Handling |
|---|---|---|
| Duplicate requests | three components ask for the same product and the server is hit three times | share one in-flight request per key |
| Repeat visits | the same data is downloaded again on every visit | keep answers for a short time |
| Stale data | old data is shown forever, or the user waits for every refresh | answer from the cache, refresh in the background |
| Out-of-order replies | a slow old reply overwrites a newer one | cancel or ignore superseded requests |
| Failure | a blank screen or a spinner that never ends | a status for each request: loading, success or error |
Stale-while-revalidate is the policy in the third row: return what you have straight away, even if it is old, and start a refresh in the background so the next reader gets newer data. The wait disappears at the cost of showing slightly old data once. The same name appears in an HTTP Cache-Control extension, but here it is applied in the client's memory.
A cache you can read
The script below builds a small cache with the three behaviours that matter first: share one in-flight request per key, treat an answer as fresh for 300 ms, and after that return the stale answer immediately while refreshing in the background. A local server counts how many times it is hit and returns that count as a version so you can see which answer you hold.
const createCache = (freshMs) => { const entries = new Map() const load = (key, path) => { const e = entries.get(key) ?? {} e.promise = fetch(BASE + path).then((r) => r.json()) .then((value) => { e.value = value; e.at = Date.now() return value }) .finally(() => { e.promise = undefined }) entries.set(key, e) return e.promise } return async (key, path) => { const e = entries.get(key) if (e?.value !== undefined) { if (Date.now() - e.at >= freshMs && !e.promise) { load(key, path).catch(() => {}) // refresh in background } return e.value // fresh or stale: answer now } return e?.promise ?? load(key, path) // share one request } }
f4.mjs: the cache.
const get = createCache(300) const ask = () => get('p', '/api/p') const first = await Promise.all([ask(), ask(), ask()]) console.log('3 callers: hits', hits, 'version', first[0].version) const again = await ask() console.log('while fresh: version', again.version, 'hits', hits) await sleep(400) // now older than 300 ms const t0 = performance.now() const stale = await ask() const quick = performance.now() - t0 < 10 console.log('when stale: version', stale.version, 'quick', quick) await sleep(200) // let the refresh finish const next = await ask() console.log('after refresh: version', next.version, 'hits', hits)
f4.mjs: the calls.
3 callers: hits 1 version 1 while fresh: version 1 hits 1 when stale: version 1 quick true after refresh: version 2 hits 2
Output (Node 24)
Three callers at once cause one request: the first call starts it, and the next two receive the same promise. A call within 300 ms is answered from memory and the server count stays at 1. After 400 ms the answer is stale, and the call returns version 1 at once, under 10 ms, while a refresh starts. The next call, after the refresh, gets version 2 and the server has been hit twice in total, once for the first load and once for the refresh. Treat the millisecond check as one sample, since timings vary from run to run on this machine.
Real libraries add more: keys with arguments, mutation that invalidates cached reads, retries and a limit on how long unused entries stay in memory. The core decision is the one above, answer now and refresh behind.
Cancellation and states
A fast typist triggers a request per keystroke, and replies do not have to come back in order, the race that the autocomplete drill in the machine coding chapter guards against. The server here answers the short query bu slowly and the longer but quickly. In the first half the page shows whichever reply arrives last, and in the second half it aborts the previous request when a new one starts.
const BASE = 'http://127.0.0.1:55831' const search = (q, signal) => fetch(`${BASE}/s?q=${q}`, { signal }).then((r) => r.json()) // 1. no cancellation: whichever answer lands last is shown let shown = '' await Promise.all(['bu', 'but'].map(async (q) => { const result = await search(q) shown = result.q console.log('arrived:', result.q) })) console.log('screen shows:', shown) // 2. abort the previous request when a new one starts shown = '' let controller const type = async (q) => { controller?.abort() controller = new AbortController() try { shown = (await search(q, controller.signal)).q console.log('arrived:', shown) } catch (e) { console.log(`dropped ${q}:`, e.name, '-', e.message) } } await Promise.all([type('bu'), type('but')]) console.log('screen shows:', shown) server.close()
f5.mjs: stale replies and AbortController.
arrived: but arrived: bu screen shows: bu dropped bu: AbortError - This operation was aborted arrived: but screen shows: but
Output (Node 24)
Without cancellation the reply for but arrives first and is then overwritten by the late reply for bu, so the screen shows results for a search the user has already changed. With AbortController, calling abort() makes the pending fetch reject with an AbortError, which the code treats as expected and ignores, and only the latest query reaches the screen.
Every request should expose a status the view can draw: loading before the first answer, success with data, or error with a message. Keep the previous data when a refresh fails, and mark it as stale rather than replacing it with an empty error screen, because old data is usually more useful to the user than none. Give errors a retry action and a message a person can read.
Three components request /api/p at the same moment. How many requests should the data layer send?
- One. The first call starts it and the others receive the same promise.
Part 5 · Rendering modes
Where the HTML is made
A page can be turned into HTML in the browser, on a server, or ahead of time. That choice decides how soon the user sees content and when the page responds to input. web.dev's article on rendering on the web is the reference for these terms.
| Mode | HTML is made | Strength | Cost |
|---|---|---|---|
| Client-side rendering (CSR) | in the browser, by JavaScript | simple hosting, fast moves between pages | blank page until code and data arrive; code size hurts responsiveness |
| Server-side rendering (SSR) | on the server for each request | content in the first response | slower first byte; needs a server |
| Static rendering | at build time, one file per URL | fastest and cheapest to serve | hard when URLs are huge or change often |
| Streaming SSR | on the server, sent in chunks | shell appears before slow data | more moving parts |
| Islands | server or static HTML plus small interactive parts | little JavaScript for mostly static pages | two models in one page |
HTML is madein the browser, by JavaScript
Strength
The same list, three ways
One local server serves the same list of 40 products three ways. /csr sends an empty shell and a script that fetches the data and builds the list. /ssr waits 300 ms for the data and sends finished HTML. /stream sends the shell at once and the list 300 ms later in the same response. The data takes 300 ms to produce, the script bundle takes 100 ms for CSR, and the hydration bundle takes 400 ms to download and 150 ms to run.
if (url === '/app.js') { // client rendering await sleep(100) return js(res, `const r = await fetch('/api/products') const items = await r.json() const item = ${item} const list = ${list} document.querySelector('#list').innerHTML = list(items) ${hydrate}`) } if (url === '/hydrate.js') { await sleep(400) // a big bundle return js(res, hydrate) } res.setHeader('content-type', 'text/html; charset=utf-8') if (url === '/csr') { // empty shell return res.end(head + button + '<ul id="list"></ul>' + '<script type="module" src="/app.js"></script>') } if (url === '/ssr') { // finished HTML await sleep(300) return res.end(head + button + `<ul>${list(products)}</ul>` + '<script src="/hydrate.js"></script>') } if (url === '/stream') { // shell first res.write(head + button + '<script src="/hydrate.js" defer></script>') await sleep(300) return res.end(`<ul>${list(products)}</ul>`) }
f6-server.mjs: the three routes.
A Playwright script opens each route in Chrome and records three times from the start of navigation, using the Element Timing API on the list items. It also clicks the button as soon as the products are in the DOM, to see whether the page responds.
const url = `http://127.0.0.1:55832/${mode}` await page.goto(url, { waitUntil: 'commit' }) await page.waitForSelector('.product') await page.click('#add') // as soon as products exist const early = await page.textContent('#add') await page.waitForFunction(() => window.hydratedAt) await sleep(200) const t = await page.evaluate(() => ({ firstByte: Math.round(performance.getEntriesByType('navigation')[0] .responseStart), shown: window.shown, works: window.hydratedAt, })) const cell = (v, w) => String(v).padEnd(w) const click = early === 'Add' ? 'ignored' : 'counted' rows.push(cell(mode, 8) + cell(t.firstByte, 12) + cell(t.shown, 15) + cell(t.works, 14) + click)
f6.mjs: measuring the three routes.
mode first byte first product button works early csr 5 608 598 counted ssr 303 336 874 ignored stream 2 320 568 ignored
Output (Chrome 157, lab, this machine, milliseconds)
Choosing a mode
The scene follows the CSR request and the SSR request side by side as a timeline of messages. It is a model of the order of events, not a recording; the times are in the table above.
Watch for when each mode shows the first product to the user
Read it as steps
The same page needs more round trips before content in CSR, but SSR waits on the server.
CSR needs more round trips before content, each one starting only after the last finished. SSR spends that time on the server, close to the data, and the browser gets finished markup in one reply, but the page is not interactive until hydration finishes. Streaming and islands are ways to shrink each of those gaps.
Pick by content and audience. A page that must be found by search and read at once, such as a product page, suits server or static rendering. A dashboard behind a login, where the user stays for an hour and every second click fetches data, suits CSR. A marketing page with one interactive widget suits islands. Whichever you choose, set a budget for the JavaScript that has to run before the page responds, because that is the cost every mode ends up paying.
In the run above, why was the early click ignored for /ssr but counted for /csr?
Part 6 · Browser storage
Five places to keep data
The browser offers several stores, and they differ in size, in whether they block the page, and in whether the data travels to the server. Choosing wrongly shows up as slow pages, lost data or leaked data.
| Store | Holds | Size | API | Sent to the server |
|---|---|---|---|---|
| Cookies | small strings | about 4 KB each | synchronous in script | yes, with matching requests |
localStorage | strings, per origin | about 5 MiB | synchronous | no |
sessionStorage | strings, per tab | about 5 MiB | synchronous | no |
| IndexedDB | structured objects, files | large, quota based | asynchronous | no |
| Cache API | request and response pairs | large, quota based | asynchronous | no |
Holdssmall strings
Sizeabout 4 KB each
Each one in Chrome
The script opens a local page whose server sets an HttpOnly cookie, and then uses each store from inside the page. It finds how long a cookie value can be, how much localStorage accepts in 1,00,000-character steps, and then stores and reads back an object in IndexedDB and a response in the Cache API.
const out = {} document.cookie = 'theme=dark; Path=/' out.cookiesScriptCanSee = document.cookie // HttpOnly one is hidden // longest value (name "big") that the cookie jar accepts let n = 4000 while (true) { const value = 'x'.repeat(n + 1) document.cookie = `big=${value}; Path=/` if (!document.cookie.includes(`big=${value}`)) break n += 1 } out.longestCookieValue = n document.cookie = 'big=; Max-Age=0; Path=/' // localStorage: add 100,000-character chunks until it refuses let chunks = 0 const chunk = 'x'.repeat(100000) try { while (true) { localStorage.setItem('k' + chunks, chunk) chunks += 1 } } catch (e) { out.localStorageError = e.name } out.localStorageChars = chunks * 100000 localStorage.clear()
f7.mjs: cookies and localStorage, run inside the page.
// IndexedDB: store an object and read it back const db = await new Promise((ok) => { const q = indexedDB.open('shop', 1) q.onupgradeneeded = () => q.result.createObjectStore('orders') q.onsuccess = () => ok(q.result) }) await new Promise((ok) => { const tx = db.transaction('orders', 'readwrite') const order = { total: 5400, lines: [1, 2] } tx.objectStore('orders').put(order, 'order-1') tx.oncomplete = ok }) out.indexedDB = await new Promise((ok) => { const store = db.transaction('orders').objectStore('orders') const g = store.get('order-1') g.onsuccess = () => ok(JSON.stringify(g.result)) }) // Cache API: store a response by request const cache = await caches.open('v1') await cache.put('/api/p', new Response('[1,2,3]')) out.cacheApi = await (await cache.match('/api/p')).text() const { quota } = await navigator.storage.estimate() out.quotaIsOverOneGiB = quota > 2 ** 30 return out })
f7.mjs: IndexedDB, Cache API and the quota.
cookiesScriptCanSee: theme=dark longestCookieValue: 4093 localStorageError: QuotaExceededError localStorageChars: 5200000 indexedDB: {"total":5400,"lines":[1,2]} cacheApi: [1,2,3] quotaIsOverOneGiB: true
Output (Chrome 157)
The script can see the theme cookie but not the HttpOnly session cookie. The longest value Chrome accepted for a cookie named big was 4,093 characters, which with the three-letter name makes 4,096 bytes, the usual limit for a whole cookie. localStorage took 52 chunks of 1,00,000 characters, 52,00,000 in all, and refused the next with QuotaExceededError, consistent with the 5 MiB limit. IndexedDB returned the object that was stored, and the Cache API returned the response body. The browser also reported a storage quota above 1 GiB for the origin.
Quotas and eviction
Storage is a loan, not a guarantee. MDN's page on quotas and eviction gives the rules. Each origin gets a quota, and browsers differ: Chromium allows an origin up to 60% of the disk, Firefox up to the smaller of 10% of the disk or 10 GiB, and Safari about 60% of the disk for browser apps. Quotas use total disk size, not free space, so an origin may not reach its limit in practice. navigator.storage.estimate() returns an estimate of usage and quota, not an exact figure.
When a device runs low on space, browsers evict whole origins, least recently used first. All data of an origin goes together, so the app never finds half its storage. Data is best-effort by default. navigator.storage.persist() asks for persistent storage, which is evicted only when the user clears it. Firefox asks the user, while Safari and Chromium decide from their own signals.
Safari adds one rule: with cross-site tracking prevention on, data that script wrote is deleted for origins the user has not interacted with in the last seven days of browser use. Server-set cookies are exempt. An app that keeps important state only in localStorage may find it gone, so keep the server as the source of truth and treat local copies as caches that can disappear.
Two other points follow. Always wrap writes in try/catch, since a write can fail on quota or in private browsing. And do not put session tokens in localStorage: any script on the page can read it, and OWASP's guidance for HTML5 storage is not to store session identifiers there. Prefer an HttpOnly cookie, which the security chapter discusses.
| Term | Meaning |
|---|---|
| View | the components that draw the screen |
| Data layer | the code that decides what to fetch and when to reuse it |
| Stale-while-revalidate | answer from the cache now and refresh in the background |