# Accessibility-Tree Queries vs DOM Implementation Coupling (a11y-tree-queries-vs-dom-selectors) Domain: testing-verification | Maturity: baseline-widely | Verified: 2026-11-16 TL;DR: CSS and data-testid selectors pass on clickable divs that screen readers and keyboards cannot reach; querying by computed ARIA role and accessible name tests the user-facing contract. Relations: - requires -> accessibility-tree-aria: Role and accessible-name queries resolve against WAI-ARIA role mappings and AccName computation. - requires -> inert-attribute-focus: Accessibility-tree queries respect aria-hidden and inert subtrees when filtering exposed controls. ## Under the Hood Role-based locators in Playwright and Testing Library run a subset of the browser's WAI-ARIA role and AccName 1.2 algorithms on the DOM subtree before matching. 1. **Implicit & Explicit Role Resolution**: The locator maps native elements (`
Saved 3 items.
``` ## Production Pitfalls - **First Rule of ARIA violation**: Replacing `
``` ## Production Pitfalls - **Calling `.show()` instead of `.showModal()`**: `.show()` activates neither the Top Layer, nor `::backdrop`, nor background inertness, leaving your modal trapped in the same `z-index` swamp you were trying to escape. - **Exit animations**: `dialog.close()` switches immediately to `display: none`; combine `@starting-style` with `transition-behavior: allow-discrete` to animate exits. - **When not to use ``**: For non-modal tooltips or dropdown menus that do not block the background, use the [Popover API](/concepts/popover-api-light-dismiss) instead. --- # Deterministic Network Interception & HAR Replay (network-interception-har-replay) Domain: testing-verification | Maturity: baseline-widely | Verified: 2026-11-16 TL;DR: Live staging APIs flake tests on rate limits and drifting data, while stubbing window.fetch hides serialization and streaming bugs; intercepting at the browser network layer replays real HTTP frames deterministically. Relations: - requires -> service-worker-lifecycle: Service Worker fetch interception handles real browser Request/Response objects in-process. - requires -> streams-api-backpressure: Network-layer mocks must preserve ReadableStream chunking and backpressure for streaming responses. ## Under the Hood Browser-level interception hooks below the `fetch()` and `XMLHttpRequest` bindings, keeping header normalization, status handling, and stream decoding intact. 1. **CDP / WebDriver BiDi Interception**: `page.route()` pauses the browser network stack before socket dispatch (`Fetch.requestPaused`), matching URL, method, and headers against handlers or an indexed `.har` archive. 2. **Service Worker Interception**: Tools like MSW register a [Service Worker](/concepts/service-worker-lifecycle) on `self.onfetch`, intercepting outgoing requests across tabs and returning synthetic `Response` objects with real `ReadableStream` bodies. 3. **HAR Replay Matching**: A recorded `.har` file stores timestamped request/response pairs, headers, and base64 payloads so tests replay exact server responses offline. ```ts // Replay recorded HTTP traffic including headers and status codes await page.routeFromHAR('tests/fixtures/checkout.har', { url: '**/api/v2/**', update: false, notFound: 'abort', }); ``` ## Production Pitfalls - **Stale HAR Drift**: Replaying a 6-month-old `.har` file hides breaking backend schema changes until production; pair HAR tests with schema contract validation. - **Broken Streaming Simulation**: Returning a single `JSON.stringify()` string in a naive mock masks [backpressure](/concepts/streams-api-backpressure) and incremental chunk-parsing bugs in SSE or AI-stream UIs. - **When not to use Network Interception**: Never mock or HAR-replay authentication redirects, CDN cache-control headers, or WebSocket upgrade handshakes in release-gate E2E suites; those require a real backend or staging environment. --- # Normalized Entity Graphs vs Document-Keyed Caches (normalized-vs-document-caches) Domain: state-architecture | Maturity: baseline-widely | Verified: 2026-11-16 TL;DR: Prevents stale duplicate records across overlapping views without 40 KB GraphQL client overhead by choosing between flat document-keyed caches and normalized entity graphs. Relations: - requires -> server-state-cache-machines: Both normalized graphs and document caches sit inside server-state cache machines to manage staleness and invalidation. ## Under the Hood A [Server State Cache Machine](/concepts/server-state-cache-machines) stores remote snapshots under one of two indexing topologies. The choice determines whether consistency happens by key invalidation or by graph pointer resolution. 1. **Document-keyed cache**: Maps `hash(url, params)` directly to the raw JSON tree. Mutations call `invalidateQueries(['users'])` to trigger background refetches, keeping client code under ~12 KB. 2. **Normalized entity graph**: Flattens nested payloads into `{ "User:42": { name: "Ada" } }` and replaces nested objects with `{ __ref: "User:42" }` pointers. 3. **Graph updates & GC**: Updating `User:42` during [Optimistic UI](/concepts/optimistic-ui-rollback) patches every view synchronously, while reference counting sweeps unreferenced entities. ```ts // Document-keyed: fast lookup, requires key invalidation on write const docCache = new Map([['GET:/team/7', { members: [{ id: 42, name: 'Ada' }] }]]); // Normalized: single source per entity, pointer-resolved on read const entityTable = new Map([['User:42', { id: 42, name: 'Ada' }]]); const queryRefs = new Map([['GET:/team/7', { members: ['User:42'] }]]); entityTable.set('User:42', { id: 42, name: 'Ada L.' }); // updates all views ``` ## Production Pitfalls - **Ghost rows in paginated lists**: Updating a normalized entity's `status` field updates its badge, yet fails to move it out of a cached `['tasks', { status: 'open' }]` page because list membership is still query-keyed. - **Silent cache misses on missing `__typename` or `id`**: Normalized clients fall back to unmerged object copies when a projection omits the primary key, causing partial UI drift. - **When not to use a normalized entity graph**: For REST/RPC APIs with flat payloads, paginated search feeds, or fewer than 3 overlapping entity views per screen, normalized graph normalization and custom cache-eviction rules add unnecessary bundle weight and stale-list bugs over document-keyed invalidation. --- # Origin Private File System (OPFS) (opfs-origin-private-fs) Domain: web-apis | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Origin-sandboxed virtual file system backed by raw OS files, offering synchronous in-place byte-range I/O inside Dedicated Workers. Relations: - requires -> dedicated-web-workers: FileSystemSyncAccessHandle is only exposed inside DedicatedWorkerGlobalScope. - under_the_hood -> indexeddb-transactions-quotas: OPFS shares the origin's storage quota pool and eviction rules with IndexedDB. ## Under the Hood If [IndexedDB](/concepts/indexeddb-transactions-quotas) is a notary public stamping every envelope, OPFS is a raw file descriptor handed directly to your [Dedicated Web Worker](/concepts/dedicated-web-workers). 1. **Private Root**: `navigator.storage.getDirectory()` returns a `FileSystemDirectoryHandle` invisible to the user's OS file picker. 2. **Exclusive Sync Handle**: Calling `fileHandle.createSyncAccessHandle()` in a worker acquires an exclusive lock and exposes `read(buf, { at })` and `write(buf, { at })`. 3. **Zero Serialization**: Bytes move straight from a Wasm linear memory `Uint8Array` to the OS file buffer without `structuredClone` or transaction wrappers. ```js // Inside a Dedicated Worker const root = await navigator.storage.getDirectory(); const file = await root.getFileHandle('db.sqlite', { create: true }); const access = await file.createSyncAccessHandle(); const page = new Uint8Array(4096); access.read(page, { at: 0 }); access.write(page, { at: 4096 }); access.flush(); access.close(); ``` ## Production Pitfalls - **Multi-tab lock contention**: `createSyncAccessHandle()` throws `NoModificationAllowedError` if another tab holds the file lock; wrap access in `navigator.locks.request()`. - **Forgetting `flush()` and `close()`**: Buffered writes may vanish on sudden tab termination, and unclosed handles block future workers from opening the file. - **When not to use OPFS**: For small key-value settings or indexed JSON queries, IndexedDB avoids manual byte-offset management and exclusive file locking. --- # Optimistic UI & Rollback Safety (optimistic-ui-rollback) Domain: state-architecture | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Applies speculative UI state immediately on user action while retaining an immutable confirmed snapshot for atomic rollback if the network request fails. Relations: - under_the_hood -> core-web-vitals-mechanics: Immediate optimistic state transitions keep perceived latency and INP presentation under 16 ms. - requires -> stale-closures-hooks: Rollback handlers must avoid closing over stale pre-mutation state when rapid consecutive edits occur. - contrasts_with -> undo-redo-structural-sharing: Optimistic rollback reverts failed pending mutations, whereas undo/redo tracks user-confirmed history via structural sharing. ## Under the Hood Optimistic UI works like an accountant's pencil-and-ink ledger: you write the expected balance in pencil right away so the customer sees instant feedback for [Core Web Vitals](/concepts/core-web-vitals-mechanics) INP, and only ink it over (or erase it) once the bank clears the check. 1. **Cancel in-flight reads**: Abort or ignore any running `GET` refetch for the same entity so an older server payload cannot clobber the new optimistic state. 2. **Snapshot & overlay**: Save the last confirmed value (or use `useOptimistic`, which overlays temporary state over base props without mutating them) and avoid [Stale Closures](/concepts/stale-closures-hooks) by reading from a functional reducer. 3. **Reconcile or rollback**: On `200 OK`, replace the speculative entry with the server's authoritative record; on `4xx`/`5xx`, revert to the snapshot and surface an explicit retry action. ```js async function toggleLike(postId, nextLiked) { const snapshot = store.get(postId); store.set(postId, { ...snapshot, liked: nextLiked, pending: true }); try { const confirmed = await api.setLike(postId, nextLiked); store.set(postId, confirmed); } catch (err) { store.set(postId, snapshot); // Atomic rollback on failure notifyRetry('Could not save like', () => toggleLike(postId, nextLiked)); } } ``` ## Production Pitfalls - **Out-of-order toggle races**: Rapidly clicking Like -> Unlike fires two requests; if Request #1 resolves slower than Request #2, naive reconciliation flickers the UI back to Liked. Use a monotonic request counter or `AbortController`. - **Fake IDs leaking into URLs**: Creating a comment optimistically with `id: "temp-123"` and letting the user click `/comments/temp-123` before the server assigns a real ID breaks deep links. - **When not to use Optimistic UI**: Never fake success on irreversible or high-stakes actions, payment charges, inventory reservations, password changes, or destructive account deletions; for local multi-step editing history, use [Undo/Redo & Structural Sharing](/concepts/undo-redo-structural-sharing) instead. --- # Paint & Rasterization (paint-rasterization) Domain: rendering-pipeline | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Paint records drawing commands into DisplayLists; Rasterization turns those vector commands into GPU-ready bitmap tiles. Relations: - requires -> render-tree-layout: Paint requires resolved box coordinates from Layout to record drawing bounds. - under_the_hood -> gpu-compositor-layers: Rasterized tiles are uploaded as GPU textures for the Compositor Thread. ## Under the Hood Paint is an architect drafting blueprints; Rasterization is the print shop turning those blueprints into tiled posters. 1. **DisplayList Recording**: The engine traverses boxes by [CSS Stacking Context](/concepts/css-stacking-context) order and appends draw calls (backgrounds, borders, text glyphs). 2. **Tile Splitting**: Layers are divided into square tiles so the engine only rasterizes regions near the viewport. 3. **Raster & Upload**: Skia or GPU shaders fill tile bitmaps and upload them as textures for [GPU Compositor Layers](/concepts/gpu-compositor-layers). ```css /* Triggers Paint only (skips Layout) when color changes */ .status-badge { background-color: #16a34a; contain: paint; /* Clips descendants and isolates invalidation */ } /* Heavy blur multiplies rasterization time per tile */ .expensive-frost { backdrop-filter: blur(24px); } ``` ## Production Pitfalls - **Giant `box-shadow` and `filter: blur()`**: Large blur radii expand paint invalidation rects and force multi-pass shader sampling per tile. - **Animating `background-color` on huge containers**: Even without Layout, repaints re-rasterize every covered tile on each frame. - **When not to use heavy paint effects**: Avoid animating `box-shadow`, `border-radius`, or `backdrop-filter` at 60fps; animate `opacity` on a pre-rendered pseudo-element instead. --- # Passive Event Listeners and Compositor Scrolling (passive-event-listeners) Domain: dom-events | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Eliminate 100ms+ mobile scroll-start jank—{ passive: true } promises the GPU compositor thread that wheel/touch listeners will never call preventDefault(). Relations: - requires -> dom-event-propagation: Passive flags are checked during hit-testing before dispatching wheel or touch propagation. - under_the_hood -> gpu-compositor-layers: Without passive listeners, the GPU compositor thread must stall scroll translation on main-thread JS. - contrasts_with -> pointer-events-touch-action: Passive listeners promise no preventDefault() in JS, whereas CSS touch-action declares scroll constraints to the compositor. ## Under the Hood The compositor thread checks a hit-tested layer's non-passive event region bit before translating a scroll gesture; if any non-passive `touchstart` or `wheel` listener is present, scrolling stalls until main-thread JS finishes. Passing `{ passive: true }` gives the compositor permanent clearance to translate the layer immediately at 120 fps. 1. **Non-Passive Slow Path**: The compositor checks a "slow scroll region" bit; if present, it waits for main-thread JS to finish running the listener before scrolling. 2. **Passive Fast Path**: The compositor translates the layer immediately and dispatches the event asynchronously. 3. **Root Default**: Chrome, Firefox, and Safari default `touchstart`, `touchmove`, and `wheel` on `window`, `document`, and `body` to `passive: true`. ```js // Analytics listener: never blocks compositor scroll scroller.addEventListener('wheel', recordScrollDelta, { passive: true }); // Custom zoomable map: explicitly opt out of passive mapCanvas.addEventListener('wheel', (e) => { e.preventDefault(); zoomMap(e.deltaY); }, { passive: false }); ``` ## Production Pitfalls - **Ignored `preventDefault()` on `document`**: Calling `e.preventDefault()` inside a document-level `wheel` listener logs a warning and fails to stop scrolling unless `{ passive: false }` is set. - **Third-Party Tracking Scripts**: Non-passive `touchstart` listeners attached to inner containers silently re-introduce scroll jank. - **When not to use `{ passive: false }`**: Avoid `{ passive: false }` on general page wrappers just to suppress scroll conditionally; use CSS `touch-action` via [Pointer Events & `touch-action`](/concepts/pointer-events-touch-action) instead. --- # PerformanceObserver & RUM Telemetry (performance-observer-rum) Domain: network-perf | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Streams real-user timing entries (LCP, INP, LoAF, resource timing) asynchronously via PerformanceObserver with buffered: true and flushes via sendBeacon. Relations: - requires -> core-web-vitals-mechanics: PerformanceObserver is the low-level browser API that emits LCP, CLS, and Event Timing entries. - requires -> bfcache-navigation: RUM scripts must flush on visibilitychange/pagehide instead of unload to preserve bfcache. ## Under the Hood Polling `performance.getEntriesByType()` on a timer is like checking your mailbox every ten milliseconds; `PerformanceObserver` acts like a push notification delivered in an idle callback whenever the engine records a [Core Web Vitals](/concepts/core-web-vitals-mechanics) entry or Long Animation Frame (`long-animation-frame`). 1. Calling `observer.observe({ type, buffered: true })` replays entries emitted before the observer attached. 2. Each `PerformanceEntry` carries high-resolution `DOMHighResTimeStamp` offsets and attribution fields (such as the LCP `element` or blocking script URL). 3. On `document.visibilityState === 'hidden'`, `navigator.sendBeacon()` hands the payload to the browser's background network queue without blocking navigation or invalidating [bfcache](/concepts/bfcache-navigation). ```js const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { queueMetric({ name: entry.name, start: entry.startTime, value: entry.duration }); } }); observer.observe({ type: 'long-animation-frame', buffered: true }); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flushWithSendBeacon(); }); ``` ## Production Pitfalls - **Forgetting `buffered: true`**: Attaching an observer after React/Vue hydrates misses early LCP and FCP entries unless `buffered: true` is set. - **Flushing on `unload`**: Using `window.addEventListener('unload', ...)` disables bfcache across your entire domain; always use `visibilitychange` or `pagehide`. - **When not to use 100% raw RUM beacons**: On high-traffic sites, sending every `resource` entry for every pageview inflates analytics bills and user battery; sample 1–5% of sessions or aggregate before flushing. --- # Pointer Events, touch-action, and Pointer Capture (pointer-events-touch-action) Domain: dom-events | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Stop mobile browser scroll from hijacking custom drags and sliders—CSS touch-action negotiates gesture ownership on the compositor while setPointerCapture() locks fast pointer streams. Relations: - requires -> dom-event-propagation: Pointer events follow standard capture/target/bubble propagation unless redirected by setPointerCapture(). - requires -> passive-event-listeners: CSS touch-action negotiates scroll ownership on the compositor without blocking passive listeners. ## Under the Hood At `touchstart`, the compositor thread reads CSS `touch-action` off the hit-tested layer to decide whether native pan/zoom owns the gesture without waiting for main-thread JS. Like painting dedicated bike lanes before rush hour, `touch-action: none` reserves the stream for your drag handler so the browser never fires `pointercancel` mid-drag. 1. **Compositor Pre-Check**: At `touchstart`, the compositor reads `touch-action` (`none`, `pan-x`, `pan-y`, `manipulation`) without waiting for JS. 2. **No `pointercancel`**: On `touch-action: none`, the browser suppresses native pan/zoom so `pointermove` streams cleanly. 3. **Pointer Capture**: Calling `el.setPointerCapture(e.pointerId)` redirects all subsequent [DOM Event Propagation](/concepts/dom-event-propagation) for that pointer straight to `el` until `pointerup`. ```js knob.addEventListener('pointerdown', (e) => { knob.setPointerCapture(e.pointerId); knob.dataset.dragging = 'true'; }); knob.addEventListener('pointermove', (e) => { if (knob.dataset.dragging === 'true') moveKnob(e.clientX); }); knob.addEventListener('pointerup', () => delete knob.dataset.dragging); ``` ## Production Pitfalls - **Missing `touch-action` on Sliders**: Forgetting `touch-action: pan-y` on a horizontal carousel causes mobile browsers to abort drags with `pointercancel`. - **Orphaned Drag State**: Relying on `pointerup` on the knob without `setPointerCapture()` drops the release event when the cursor leaves the element. - **When not to use `touch-action: none`**: Never apply `touch-action: none` to large scrollable sections, it traps mobile users who try to scroll past the widget. --- # Popover API (HTML popover Attribute) (popover-api-light-dismiss) Domain: dom-events | Maturity: baseline-newly | Verified: 2026-11-15 TL;DR: Declarative HTML attribute rendering menus, tooltips, or toasts in the Top Layer with automatic light-dismiss and zero JavaScript. Relations: - requires -> native-dialog-element: Reuses the engine's Top Layer mechanism without making the rest of the document inert. - contrasts_with -> roving-tabindex-focus-order: Popover handles Top Layer light-dismiss, while roving tabindex manages arrow-key focus inside menus. ## Under the Hood 1. An element with `popover="auto"` enters the Top Layer (shared with the [Native `` Element](/concepts/native-dialog-element)) when its `popovertarget` button is clicked, without blocking background interaction. 2. The engine maintains an internal stack of open `auto` popovers: opening a second popover closes the previous one automatically (unless it is a direct ancestor). 3. Any `pointerdown` outside the popover or pressing `Escape` triggers native *light-dismiss* without fragile [DOM Event Propagation](/concepts/dom-event-propagation) hacks. ```html
``` ## Production Pitfalls - **Confusing `auto` and `manual`**: A notification toast using `popover="auto"` vanishes as soon as the user clicks anywhere; use `popover="manual"` for persistent toasts. - **Anchor positioning**: `popover` does not automatically position the surface next to its trigger; pair it with CSS Anchor Positioning or lightweight coordinate math. - **When not to use `popover`**: For a critical page-blocking modal (such as a destructive confirmation), use `.showModal()`. For arrow-key navigation across menu items inside a popover, pair it with [Roving Tabindex](/concepts/roving-tabindex-focus-order). --- # Preload Scanner and fetchpriority Attribute (preload-scanner-hints) Domain: network-perf | Maturity: baseline-newly | Verified: 2026-11-15 TL;DR: Speculative HTML scanner discovering critical resources before JS execution, paired with fetchpriority to reorder the HTTP/2-HTTP/3 queue. Relations: - under_the_hood -> browser-rendering-pipeline: Governs availability of critical resources (CSS, fonts, LCP hero image) prior to first Paint. - contrasts_with -> speculation-rules-prerender: Preload scanner prioritizes current-page subresources, while Speculation Rules prerender next-page navigations. ## Under the Hood Treat the Preload Scanner as an airport baggage advance scout: while the main HTML parser is stuck at security behind a blocking ` ``` ## Production Pitfalls - **Hydration mismatch cascades**: Rendering `Date.now()` or `window.matchMedia` during SSR causes client hydration to throw away the server DOM and repaint from scratch. - **Uncached lazy chunks on slow 3G**: Resumability trades boot JS for interaction-time chunk fetches; prefetch probable handlers via a Service Worker or `` so clicks stay under 200 ms INP. - **When not to use Resumability**: In dense, always-interactive single-page tools (Figma-like canvases, IDE editors) where 95% of UI handlers are needed within the first second anyway. --- # Roving Tabindex and Focus Order Mechanics (roving-tabindex-focus-order) Domain: security-a11y | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Keyboard navigation pattern that reduces a multi-item composite widget to a single Tab stop by toggling tabindex='0' onto the active descendant while keeping siblings at tabindex='-1'. Relations: - requires -> accessibility-tree-aria: Roving tabindex pairs with composite ARIA roles (tablist, menu, toolbar) so screen readers announce item positions. - under_the_hood -> dom-event-propagation: A single keydown listener on the container intercepts Arrow keys via event bubbling. ## Under the Hood Without roving `tabindex`, a 40-button toolbar forces keyboard users to mash `Tab` forty times just to reach the next section; roving `tabindex` turns the entire toolbar into one exit-ramps-included roundabout. 1. **Sequential Focus Order**: The browser's `Tab` walker visits elements with `tabindex="0"` in DOM order and skips `tabindex="-1"`, though `element.focus()` still moves focus to `-1` nodes. 2. **Delegated Key Listener**: A single `keydown` handler on the parent container intercepts `ArrowLeft`/`ArrowRight` (or `Home`/`End`) via [DOM Event Propagation](/concepts/dom-event-propagation). 3. **Focus Restoration**: Leaving the widget via `Tab` and returning later via `Shift+Tab` lands directly on the last active item because its `tabindex` remained `0` in the [Accessibility Tree](/concepts/accessibility-tree-aria). ```js toolbar.addEventListener('keydown', (e) => { const items = [...toolbar.querySelectorAll('[role="button"]')]; const idx = items.indexOf(document.activeElement); if (idx === -1) return; const next = e.key === 'ArrowRight' ? (idx + 1) % items.length : e.key === 'ArrowLeft' ? (idx - 1 + items.length) % items.length : -1; if (next === -1) return; items[idx].tabIndex = -1; items[next].tabIndex = 0; items[next].focus(); }); ``` ## Production Pitfalls - **Using positive `tabindex > 0`**: Even a single `tabindex="1"` hijacks the entire document's `Tab` order ahead of skip links and navigation; restrict values to `0` and `-1`. - **Removing the active node without shifting `tabindex="0"`**: Deleting the currently active tab without promoting a neighbor leaves the widget unreachable by keyboard `Tab`. - **When not to use roving `tabindex`**: Virtualized lists with 10,000 off-screen rows cannot mount DOM nodes to focus; use `aria-activedescendant` on the scroll container instead. --- # Server Actions & Serialized Closure Boundaries (rpc-server-actions-closures) Domain: framework-internals | Maturity: baseline-newly | Verified: 2026-11-16 TL;DR: Server Actions look like local async functions, yet every invocation crosses an unauthenticated HTTP boundary. Treating closures as free local scope leaks server secrets or crashes with non-serializable payload errors. Relations: - requires -> structured-clone-algorithm: Arguments and return values crossing the server-client boundary must be acyclic and serializable. - requires -> optimistic-ui-rollback: UI mutations wrap Server Action invocations in optimistic state that rolls back if the RPC rejects. ## Under the Hood The bundler splits a `"use server"` module into a server-only handler map and a thin client RPC stub. 1. **Action ID & Closure Capture**: At build time, the compiler replaces the server function with `createServerReference(actionId)`. Any lexical variable captured from an enclosing Server Component is encrypted and bound via `.bind(null, encryptedClosure)`. 2. **Wire Transport**: Calling the stub serializes arguments (and bound closure tokens) into a `POST` request with a `Next-Action` (or framework RPC) header. 3. **Server Dispatch & Revalidation**: The server runtime looks up `actionId`, decrypts bound closure arguments, executes the handler, and streams updated UI fragments back in the same HTTP response. ```tsx // Server Component captures `orgId` into a hidden encrypted closure export default function InviteForm({ orgId }: { orgId: string }) { async function inviteMember(formData: FormData) { 'use server'; // Must re-verify session & orgId authorization here! const user = await requireSession(); await db.invites.create({ orgId, email: String(formData.get('email')), by: user.id }); } return
; } ``` ## Production Pitfalls - **Missing Authorization Checks Inside Actions**: Because every `"use server"` function is a public HTTP `POST` endpoint, attackers can replay `actionId` with forged payloads if the handler skips session/RBAC verification. - **Non-Serializable Arguments**: Passing class instances, `Map` callbacks, or DOM events to a Server Action throws runtime serialization errors across the wire boundary. - **When not to use Server Actions**: Never use Server Actions for cacheable `GET` data reads or public webhook ingestion; `POST`-only RPC endpoints bypass CDN edge caching and serialize sequentially in some frameworks. --- # Runtime Boundary Validation (Parse, Don't Validate) (runtime-boundary-validation) Domain: state-architecture | Maturity: baseline-widely | Verified: 2026-11-16 TL;DR: Prevents silent TypeError crashes from drifted API payloads and corrupted localStorage by parsing untrusted JSON at I/O boundaries into typed structures without blocking INP. Relations: - requires -> structured-clone-algorithm: Cross-boundary messages via postMessage and IndexedDB strip prototypes and bypass TypeScript compile-time types. - requires -> long-tasks-and-inp: Synchronous schema validation over huge arrays can exceed 50 ms on the main thread and degrade INP. ## Under the Hood Every `JSON.parse()` call and [Structured Clone](/concepts/structured-clone-algorithm) boundary returns `unknown` at runtime. Boolean `validate(x)` checks discard proof of structure, whereas a parser refines the type and strips unexpected keys in one pass. 1. **Boundary isolation**: Run schema parsing once in the network, storage, or Worker adapter rather than inside render functions. 2. **Non-throwing `safeParse`**: Return a discriminated `{ success, data | error }` result so corrupted `localStorage` entries fall back to defaults instead of crashing hydration. 3. **Chunked large lists**: Offload multi-megabyte array parsing to a Dedicated Worker or validate lazily to avoid [Long Tasks](/concepts/long-tasks-and-inp). ```ts import { z } from 'zod'; const UserSchema = z.object({ id: z.string(), role: z.enum(['admin', 'viewer']) }); type User = z.infer; export async function fetchUser(url: string): Promise { const raw: unknown = await (await fetch(url)).json(); const parsed = UserSchema.safeParse(raw); if (!parsed.success) throw new Error(`Schema drift: ${parsed.error.message}`); return parsed.data; } ``` ## Production Pitfalls - **White-screen crash on stale `localStorage` schema**: Deploying a renamed field without `safeParse` fallback throws during initial state hydration for returning users. - **50 ms+ main-thread stall on 5,000-row tables**: Running deep recursive object validation synchronously inside a click handler blocks paint frames and spikes INP. - **When not to use runtime schema parsing**: Inside 60 fps animation loops, `requestAnimationFrame` physics ticks, or already-parsed internal reducer transitions where data never crossed an untrusted serialization boundary. --- # Prioritized Task Scheduling and scheduler.yield() (scheduler-api-yield) Domain: js-runtime | Maturity: interop-experimental | Verified: 2026-11-15 TL;DR: Cooperative main-thread yielding primitive that pauses long JS work for input and rendering, then resumes in a prioritized continuation queue. Relations: - requires -> event-loop-tasks-microtasks: scheduler.yield() exits the current macrotask so the Event Loop can process input and paint. - requires -> promises-async-await-internals: await scheduler.yield() suspends the async function context until the continuation task fires. - under_the_hood -> performance-observer-rum: PerformanceObserver longtask and LoAF entries measure the main-thread stalls that scheduler.yield() breaks up. - contrasts_with -> regexp-backtracking-unicode: scheduler.yield() pauses between loop iterations, whereas catastrophic regex backtracking stalls a single synchronous call frame. ## Under the Hood Picture stepping aside at a grocery checkout so a shopper with one item (`click` event) can pay, while keeping your place right behind them instead of walking to the back of the store line (`setTimeout(0)`). 1. **Task Break**: Calling `await scheduler.yield()` unwinds the active task and yields control to the browser scheduler. 2. **Input & Frame Window**: Pending high-priority input events and `Update the Rendering` execute immediately. 3. **Continuation Priority**: The engine places the resumed chunk in a dedicated continuation queue that drains before normal `postTask` or third-party timers. ```js const yieldMain = () => globalThis.scheduler?.yield?.() ?? new Promise((r) => setTimeout(r, 0)); async function processBatch(items) { let sliceStart = performance.now(); for (const item of items) { transform(item); if (performance.now() - sliceStart > 16) { await yieldMain(); sliceStart = performance.now(); } } } ``` ## Production Pitfalls - **Yielding Every Iteration**: Calling `await yieldMain()` on every loop step adds massive async overhead; gate it with a 12ms–16ms `performance.now()` budget. - **Missing Fallback**: Safari and older Firefox versions lack `scheduler.yield()`; always feature-detect before calling. - **When not to use `scheduler.yield()`**: Never run heavy pure computation (image encoding, crypto, AST parsing, or [catastrophic RegExp backtracking](/concepts/regexp-backtracking-unicode)) on the main thread at all; move it to a Web Worker, and track remaining stalls via [PerformanceObserver RUM](/concepts/performance-observer-rum). --- # Scroll-Driven Animations (scroll-driven-animations) Domain: rendering-pipeline | Maturity: interop-experimental | Verified: 2026-11-15 TL;DR: animation-timeline: scroll() and view() bind CSS and WAAPI animations directly to scroll progress on the Compositor Thread. Relations: - requires -> web-animations-api: Scroll-driven timelines plug into the same Web Animations timing model. - requires -> gpu-compositor-layers: Scroll progress updates on the Compositor Thread without main-thread scroll listeners. ## Under the Hood A JS scroll listener is a backseat driver shouting coordinates over a walkie-talkie; `animation-timeline` wires the speedometer directly to the axle. 1. **Timeline Replacement**: Instead of wall-clock time, [Web Animations API](/concepts/web-animations-api) timelines sample progress from `0%` to `100%` based on scroll offset. 2. **Compositor Execution**: When animating [GPU Compositor Layers](/concepts/gpu-compositor-layers) properties like `transform: scaleX()` or `opacity`, the Compositor Thread updates pixels without waking the main thread. 3. **Named Ranges**: `animation-range: entry 0% cover 40%` scopes `view()` animations to exact entry and exit phases. ```css @supports (animation-timeline: view()) { .reveal-card { animation: fade-slide linear both; animation-timeline: view(); animation-range: entry 0% entry 80%; } } ``` ## Production Pitfalls - **Missing `@supports` guard**: Setting `opacity: 0` at `0%` leaves elements permanently invisible in browsers lacking `animation-timeline` support. - **Animating `width` instead of `scaleX()`**: Using `width` forces Layout on every scroll tick, forfeiting compositor offloading. - **When not to use Scroll-Driven Animations**: Do not use them for critical navigation state or binary sticky-header triggers where `IntersectionObserver` or `position: sticky` suffices. --- # Server State Cache Machines (fresh → stale → fetching) (server-state-cache-machines) Domain: framework-internals | Maturity: baseline-widely | Verified: 2026-11-16 TL;DR: Stop firing duplicate API requests on every component mount or tab switch. A deterministic cache state machine deduplicates in-flight fetches, serves stale memory in 0 ms, and revalidates in the background. Relations: - requires -> http-caching-directives: Client cache machines mirror HTTP Cache-Control stale-while-revalidate semantics in JavaScript heap memory. - requires -> beacon-api-visibilitychange: Tab refocus triggers visibilitychange listeners that transition stale cache entries back to fetching. ## Under the Hood A cache machine indexes every query by a deterministic serialized key in a `Map`. Multiple mounted observers subscribe to the same entry instead of owning independent `fetch` lifecycles. 1. **In-Flight Deduplication**: When an observer mounts for a key with an active `Promise`, the machine returns the existing promise reference instead of opening a second TCP/HTTP stream. 2. **Stale-While-Revalidate (SWR)**: If `Date.now() - updatedAt < staleTime`, the entry stays `fresh` and returns cached data synchronously. Once `staleTime` expires, reads still return stale data in 0 ms while dispatching a background refetch. 3. **Observer Reference Counting & GC**: Each mounted component increments `observers.size`. When `observers.size` hits `0`, a `gcTime` timer starts; if no observer remounts before expiry, V8 reclaims the entry. ```ts class QueryEntry { state: 'fresh' | 'stale' | 'fetching' = 'fetching'; data?: T; updatedAt = 0; inflight: Promise | null = null; fetch(fetcher: () => Promise, staleTime: number): Promise { if (this.inflight) return this.inflight; if (this.data && Date.now() - this.updatedAt < staleTime) return Promise.resolve(this.data); this.state = 'fetching'; return (this.inflight = fetcher().then((res) => { Object.assign(this, { data: res, updatedAt: Date.now(), state: staleTime > 0 ? 'fresh' : 'stale', inflight: null }); return res; })); } } ``` ## Production Pitfalls - **Thundering Herd on `staleTime: 0`**: Defaulting `staleTime` to `0` marks every response immediately stale, causing a full refetch burst whenever a user switches browser tabs or remounts a list. - **Unstable Object Keys**: Passing inline objects with randomized property order or unmemoized functions as query keys defeats `Map` lookup and leaks entries until `gcTime` expires. - **When not to use a client cache machine**: Never put high-frequency ephemeral streams (60 fps WebSocket telemetry, local drag coordinates) into a serialized query cache; key hashing and subscriber notifications add unnecessary heap allocations. --- # Service Worker Lifecycle (service-worker-lifecycle) Domain: network-perf | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Runs an off-thread programmable network proxy through install, waiting, and activate states—ensuring one consistent asset version per open tab. Relations: - requires -> http-caching-directives: sw.js itself must be served with no-cache so browser update checks detect new worker bytes. - under_the_hood -> event-loop-tasks-microtasks: Service workers execute in an isolated worker event loop and wake only for functional events. ## Under the Hood A Service Worker runs on its own [Event Loop](/concepts/event-loop-tasks-microtasks) thread with zero DOM access, acting like a local reverse proxy inside the browser. Because two tabs of the same origin share one worker, the spec enforces strict version handoff rules: 1. On navigation, the browser checks `sw.js` for a single byte difference (governed by [HTTP Caching Directives](/concepts/http-caching-directives)). 2. If changed, `v2` runs `install` in the background while `v1` keeps serving existing tabs. 3. `v2` enters the `waiting` state until every `v1`-controlled tab closes, unless `self.skipWaiting()` forces immediate takeover. 4. Once `activate` runs, `v2` purges stale `CacheStorage` buckets and intercepts `fetch` events. ```js self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((keys) => Promise.all( keys.filter((k) => k !== CACHE_VERSION).map((k) => caches.delete(k)) ) ) ); }); ``` ## Production Pitfalls - **Blindly calling `skipWaiting()`**: Forcing `v2` to take over an open `v1` tab causes lazy-loaded `v1` dynamic imports to fail with `ChunkLoadError` or serve `v2` modules to `v1` HTML. - **Long `max-age` on `sw.js`**: Caching `sw.js` with `max-age=31536000` locks users onto an old worker for a year; always serve `sw.js` with `Cache-Control: no-cache`. - **When not to use a Service Worker**: On content sites that only need fast static asset caching, HTTP `immutable` headers and CDN edge caching deliver zero startup latency without worker thread wakeups. --- # Shadow DOM Encapsulation and Event Retargeting (shadow-dom-encapsulation) Domain: dom-events | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Isolate component CSS and DOM trees without iframes—Shadow DOM blocks outer selectors, projects light DOM via , and retargets bubbling events to the host. Relations: - requires -> dom-event-propagation: Shadow trees modify event propagation by retargeting event.target to the host at the ShadowRoot. - contrasts_with -> css-cascade-layers: Cascade Layers organize light-DOM specificity; Shadow DOM creates a hard selector boundary. - contrasts_with -> mutation-observer: Outer MutationObserver instances stop at the ShadowRoot boundary unless attached inside the shadow tree. ## Under the Hood Blink attaches a `ShadowRoot` as an encapsulated subtree whose styles and IDs are scoped away from document selectors, then merges `` placeholders with light-DOM children in the flat tree for layout. When a composed event bubbles past the `ShadowRoot` boundary, the engine rewrites `event.target` to the host element. 1. **Flat Tree Composition**: The layout engine merges `` elements with slotted light-DOM children without moving nodes in the actual DOM. 2. **Hard Style Boundary**: Document selectors stop at the `ShadowRoot`; only inheritable properties (`color`, `font`) and CSS custom properties cross inward, unlike [CSS Cascade Layers](/concepts/css-cascade-layers). 3. **Event Retargeting**: Built-in UI events (`click`, `input`) have `composed: true` and retarget `e.target` to the host; custom events default to `composed: false` and stop at the boundary. ```html Verified ``` ## Production Pitfalls - **Broken `for`/`aria-labelledby` IDs**: ID references cannot cross `ShadowRoot` boundaries; keep labels and inputs in the same tree, and attach any [MutationObserver](/concepts/mutation-observer) directly to the shadow root if you need to observe internal changes. - **Lost Design-System Typography**: Global CSS resets (`button { font: inherit }`) do not enter shadow trees; share tokens via CSS custom properties or constructable `adoptedStyleSheets`. - **When not to use Shadow DOM**: Never wrap ordinary application pages or forms in Shadow DOM, it breaks global form submission, accessibility IDs, and utility CSS unless paired with `ElementInternals`. --- # SharedArrayBuffer and Atomics Synchronization (shared-array-buffer-atomics) Domain: web-apis | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Shared linear memory pages mapped across multiple JS threads, synchronized with hardware atomic operations and futex wait/notify queues. Relations: - requires -> dedicated-web-workers: SharedArrayBuffer exists to share raw binary memory concurrently with Web Workers. - under_the_hood -> cross-origin-isolation-coop-coep: Browsers gate SharedArrayBuffer behind crossOriginIsolated to mitigate Spectre timing attacks. - contrasts_with -> typed-arrays-zero-copy: SharedArrayBuffer shares memory concurrently across threads, whereas ArrayBuffer transferables move exclusive ownership. ## Under the Hood `SharedArrayBuffer` turns separate [Dedicated Web Workers](/concepts/dedicated-web-workers) from isolated offices into surgeons sharing one operating table: without `Atomics` locks, two hands reaching for the same byte corrupt the state. 1. **Isolation Gate**: Engines expose `SharedArrayBuffer` only when [Cross-Origin Isolation](/concepts/cross-origin-isolation-coop-coep) is active (`self.crossOriginIsolated === true`). 2. **Memory Ordering**: Plain `TypedArray` writes may reorder across CPU cores; `Atomics.store`, `Atomics.load`, and `Atomics.compareExchange` emit hardware memory barriers. 3. **Thread Parking**: `Atomics.wait(int32View, idx, expected)` suspends a worker thread at zero CPU cost until another agent calls `Atomics.notify`. ```js // Worker thread: block until slot 0 changes from 0 const view = new Int32Array(sharedBuffer); Atomics.wait(view, 0, 0); const payloadLength = Atomics.load(view, 1); // Main thread: write payload length, flip flag, wake worker Atomics.store(view, 1, 1024); Atomics.store(view, 0, 1); Atomics.notify(view, 0, 1); ``` ## Production Pitfalls - **Calling `Atomics.wait()` on the main thread**: Throws a `TypeError` synchronously; use `Atomics.waitAsync()` if the UI thread must observe a shared slot. - **Data races on non-atomic views**: Mixing plain `view[0] = 1` with `Atomics.load(view, 0)` causes torn reads on 64-bit values or stale CPU cache lines. - **When not to use `SharedArrayBuffer`**: Standard request/response worker tasks work cleanly with [TypedArrays & Zero-Copy Transfers](/concepts/typed-arrays-zero-copy) via `postMessage` and avoid COOP/COEP deployment constraints on third-party embeds. --- # Simulated DOM (JSDOM/HappyDOM) vs Real Browser Engines (simulated-dom-vs-real-engines) Domain: testing-verification | Maturity: baseline-widely | Verified: 2026-11-16 TL;DR: Green JSDOM tests ship broken layouts because Node.js DOM shims lack a layout engine, returning zeros for geometry and ignoring stacking contexts and CORS. Relations: - requires -> render-tree-layout: Real browser engines compute box geometry during layout; simulated DOMs return static zeros. - requires -> css-stacking-context: Hit-testing and pointer interception depend on stacking context paint order absent in JSDOM. - requires -> cors-preflight-samesite: Simulated fetch mocks bypass browser CORS preflight and SameSite cookie enforcement. ## Under the Hood Blink, Gecko, and WebKit run a multi-stage C++ pipeline from HTML parsing to GPU compositing. Simulated DOM libraries reimplement only the JavaScript object model in Node.js and stub out geometry. 1. **No CSSOM or Box Tree**: JSDOM parses inline styles into strings but never runs cascade resolution or [Render Tree Layout](/concepts/render-tree-layout), so `offsetWidth` and `getBoundingClientRect()` return `0`. 2. **Missing Hit-Testing**: `elementFromPoint()` and synthetic clicks in JSDOM dispatch DOM events directly on the target node without checking `pointer-events: none`, `z-index` occlusion, or `overflow: hidden` clipping. 3. **Permissive Network Stack**: Node.js `undici` or mocked `fetch()` skips browser origin policies, `SameSite` cookie jars, and mixed-content blocks. ```ts // JSDOM passes even when an overlay blocks the button test('submit button geometry', () => { document.body.innerHTML = ``; const btn = document.querySelector('button')!; expect(btn.getBoundingClientRect().width).toBe(0); // JSDOM stub }); ``` ## Production Pitfalls - **Invisible Occlusion Bugs**: A modal backdrop with `z-index: 50` covers a submit button in production, yet JSDOM `fireEvent.click(btn)` succeeds because it never executes hit-testing. - **False-Negative ResizeObserver Tests**: Components relying on `ResizeObserver` or `IntersectionObserver` never receive real viewport intersections in Node.js unless manually mocked, hiding infinite-loop layout bugs. - **When not to use Simulated DOMs**: Never validate sticky positioning, scroll-snap thresholds, `getBoundingClientRect()` measurements, focus-trap visibility, or [CORS](/concepts/cors-preflight-samesite) cookie flows in JSDOM or HappyDOM; execute those assertions inside a real headless browser engine. --- # Speculation Rules & Prerendering (speculation-rules-prerender) Domain: network-perf | Maturity: interop-experimental | Verified: 2026-11-15 TL;DR: Declarative JSON rules that prefetch or fully prerender predicted next navigations in a hidden browsing context, delivering near-instant 0 ms LCP on click. Relations: - contrasts_with -> preload-scanner-hints: Preload fetches subresources for the current page; Speculation Rules fetches or prerenders full future navigations. - contrasts_with -> bfcache-navigation: bfcache accelerates Back/Forward history traversal; Speculation Rules accelerates forward navigations. ## Under the Hood While [bfcache](/concepts/bfcache-navigation) handles instant Back/Forward navigation and the [Preload Scanner](/concepts/preload-scanner-hints) handles subresources on the current page, Speculation Rules tackle forward clicks. Think of it as staging the next theater set behind a closed curtain before the scene change. 1. A ` ``` ## Production Pitfalls - **Inflated analytics & ad beacons**: Scripts that fire on `DOMContentLoaded` count phantom pageviews for every hovered link; gate telemetry on `!document.prerendering` and `prerenderingchange`. - **`eagerness: immediate` on large lists**: Putting `immediate` on a 30-item catalog grid DDoS-attacks your own origin server on every page load. - **When not to use `prerender`**: Avoid prerendering URLs with server-side side effects (logout links, add-to-cart GET endpoints) or pages heavy on WebGL/video memory. --- # Stale Closures in Hooks & Callbacks (stale-closures-hooks) Domain: state-architecture | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Explains how JavaScript lexical closures snapshot primitive state per render, causing timers, listeners, and suppressed dependency arrays to read outdated values. Relations: - requires -> virtual-dom-reconciliation: Each VDOM re-render invokes the component function anew, creating fresh lexical scopes. - under_the_hood -> event-loop-tasks-microtasks: Deferred timers and promises execute long after the render call stack that created their closure popped. - contrasts_with -> fine-grained-signals: Signals pass a stable box reference whose .get() always reads the current value without stale closures. - contrasts_with -> url-as-state-store: Hook closures snapshot per-render filter state, whereas URL search params act as a single external source of truth. ## Under the Hood A stale closure is standard ECMAScript lexical scoping colliding with [Virtual DOM](/concepts/virtual-dom-reconciliation) re-renders and [Event Loop](/concepts/event-loop-tasks-microtasks) callbacks. Each render prints a dated Polaroid: a timer created in Render #1 carries that Polaroid even after Render #10 hangs a newer photo. 1. Render #1 declares `const count = 0` and passes `() => setCount(count + 1)` to `setInterval`. 2. When the timer fires 1,000 ms later, V8 resolves `count` against Render #1's `LexicalEnvironment` (`0`), writing `1` every single tick. 3. Passing a functional updater `c => c + 1`, reading a mutable `.current` ref, or switching to [Fine-Grained Signals](/concepts/fine-grained-signals) (which pass a live box rather than a frozen primitive) eliminates the snapshot drift. ```js // Buggy: closes over Render #1's `count` useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); return () => clearInterval(id); }, []); // eslint-disable-next-line react-hooks/exhaustive-deps // Fixed: functional updater reads latest state from the queue useEffect(() => { const id = setInterval(() => setCount((c) => c + 1), 1000); return () => clearInterval(id); }, []); ``` ## Production Pitfalls - **Silencing `react-hooks/exhaustive-deps`**: Adding `// eslint-disable-next-line` to force an effect to run once is the fastest way to ship stale auth tokens or outdated filters in WebSocket handlers. - **Debounced callbacks capturing old props**: Creating a debounced `save()` inside render without memoizing or reading a ref sends yesterday's form state to the API. - **When not to use `useRef` to bypass dependencies**: Don't stuff reactive UI state into a ref just to silence a linter, if the effect should re-run when `userId` changes, keep `userId` in the dependency array, or move filter/navigation state to [URL as State Store](/concepts/url-as-state-store). --- # Client State Topology: Ephemeral, URL, Server Cache & Persistent (state-topology-boundaries) Domain: state-architecture | Maturity: baseline-widely | Verified: 2026-11-16 TL;DR: Eliminates stale data, broken back-button navigation, and redundant re-renders by assigning every piece of UI state to its canonical owner: ephemeral memory, URL search params, a server cache, or IndexedDB. Relations: - requires -> url-as-state-store: Shareable filters, pagination, and active tabs belong in URLSearchParams rather than in-memory stores. - requires -> server-state-cache-machines: Remote entities require staleness tracking, deduplication, and background revalidation instead of manual store slices. ## Under the Hood Every client state variable has an authoritative lifecycle and a serialization boundary. Assigning state to the wrong tier forces manual synchronization code that drifts out of sync across renders and navigations. 1. **Ephemeral UI state**: Hover flags, modal open toggles, and draft input text live in component memory and unmount with the DOM subtree. 2. **Navigational URL state**: Filters, sort order, and pagination serialize into `URLSearchParams` via [URL as State Store](/concepts/url-as-state-store) so reloads and shared links restore the exact view. 3. **Server cache state**: Remote records belong to a dedicated [Server State Cache Machine](/concepts/server-state-cache-machines) that tracks `staleTime`, deduplicates in-flight fetches, and invalidates on mutation. 4. **Durable client state**: Offline drafts and user preferences write asynchronously to [IndexedDB](/concepts/indexeddb-transactions-quotas) to survive tab termination. ```ts type Topology = { ephemeral: { dropdownOpen: boolean }; url: URLSearchParams; // ?page=2&sort=asc serverCache: Map; persistent: IDBDatabase; // offline drafts & auth metadata }; function selectOwner(isRemote: boolean, isShareable: boolean, isDurable: boolean) { if (isRemote) return 'serverCache'; if (isShareable) return 'url'; if (isDurable) return 'persistent'; return 'ephemeral'; } ``` ## Production Pitfalls - **Back button resets search filters**: Storing pagination or filter facets in memory instead of `URLSearchParams` wipes user context on history pop or link sharing. - **Mirroring server cache into local state**: Copying fetched rows into component state on mount disconnects the view from background revalidation and serves stale mutations. - **When not to use URL state**: Never serialize high-frequency coordinates (drag offsets, canvas pan) or sensitive PII tokens into `history.replaceState()`; Blink throttles `replaceState` after 100 calls per 30 seconds and URLs leak into browser history and `Referer` headers. --- # Streaming SSR & Progressive Flushing (streaming-ssr-flushing) Domain: network-perf | Maturity: baseline-widely | Verified: 2026-11-15 TL;DR: Streams the HTML and shell immediately over HTTP/2+ while slow backend queries run, then flushes deferred