Kayavak / Recaps / The Web Frontend
Recaps · Volume 2
The Web Frontend
The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.
12
Key ideas
- The browser is a platform: it runs untrusted code from many origins side by side, isolates them, and exposes capabilities through web APIs.
- A URL = scheme, host, port, path, query, fragment; build and parse with
URL and URLSearchParams, never by string concatenation. The fragment is never sent.
- An origin = scheme + host + port; a site = scheme + registrable domain (eTLD+1, from the Public Suffix List). Cookies and
SameSite work per site; storage and the same-origin policy work per origin.
- A browsing context / navigable (tab, iframe, popup) hosts one document at a time; navigations create history entries;
history.pushState and the Navigation API change the URL without loading a document.
- Loading: the parser builds the DOM top to bottom; classic scripts block it;
defer and modules run after parsing in order; async runs on arrival; CSS blocks rendering (and classic scripts that follow it).
- Three trees: DOM (content), CSSOM (styles), accessibility tree (what assistive tech sees); rendering combines DOM and CSSOM (chapter 18).
- The JavaScript runtime in a page: one main thread, an event loop, tasks and microtasks, plus workers for parallelism (chapters 15 and 29).
- Storage: cookies (sent with requests), Web Storage (sync, strings), IndexedDB (async, structured clone), Cache Storage, OPFS; all best-effort and evictable unless persisted.
- Security layers: same-origin policy, CORS opt-in, site isolation, the sandbox, secure contexts, permissions, opt-in headers (CSP, COOP/COEP, frame-ancestors, HSTS).
- Page lifecycle:
DOMContentLoaded, load, visibilitychange, pagehide/pageshow, freeze/resume; avoid unload (it blocks the bfcache and is being removed).
Numbers to remember
- localStorage: about 5 million characters per origin, synchronous.
- Cookie: about 4 KB each, about 50+ per domain; all matching cookies travel with every request.
- Chromium quota: the browser up to 80% of disk, one origin up to 60%; Safari may evict script-writable storage after 7 days without user interaction.
- Default ports: 80 (http), 443 (https), so they're omitted from origins.
Pitfalls
- Treating
localhost and 127.0.0.1 (or www and the apex domain) as the same origin.
- Expecting CORS to protect a server: the request is still sent and processed.
- Parser-blocking scripts in the
<head>; relying on async scripts' order.
- Reading attributes when you need live properties (
value, checked).
- Storing objects in
localStorage without JSON.stringify.
- Using
unload for saving state (unreliable on mobile, blocks the bfcache); use visibilitychange/pagehide.
- Keeping the only copy of user data in browser storage.
Glossary
- eTLD+1: effective top-level domain plus one label (
example.co.in), the registrable domain.
- Navigable: the spec's term for a tab or frame that can navigate between documents.
- Secure context: a page loaded over HTTPS or from localhost; required for powerful APIs.
- Opaque origin: an origin that equals nothing, not even itself (
file:// pages, sandboxed iframes), serialised as null.
- Structured clone: the algorithm that copies values for IndexedDB,
postMessage and workers.
- bfcache: the back-forward cache holding whole pages in memory for instant Back/Forward.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "If my server's URL parser says the host is X, the browser goes to X." |
Different parsers resolve some strings to different hosts. |
| "UTF-8 is the default for web pages." |
Without a declared charset, browsers fall back to a locale-dependent legacy encoding. |
"Allowing Origin: null is harmless; it's for local files." |
Every sandboxed frame and data: page has origin null. |
| "Zero-delay timers are free." |
Nested ones are clamped to 4 ms, and background tabs are throttled harder. |
| "CORS stops requests from other sites." |
It stops other sites from reading responses; the request still arrives and acts. |
| "Same site means same origin." |
Sites group origins by registrable domain; cookies follow sites, storage follows origins. |
13
Key ideas
- A document is
<!doctype html>, <html lang>, a <head> (charset, viewport, title, links, scripts) and a <body>.
- Choose elements for meaning: landmarks (
header, nav, main, aside, footer), sectioning (article, section), headings in structural order, lists, tables for data, <a href> to go somewhere, <button> to do something.
- Implicit semantics: native elements map to accessibility roles automatically (
nav → navigation, button → button, ul → list); ARIA only fills gaps, and "no ARIA is better than bad ARIA".
- Content models define what may nest where (no interactive content inside
<a> or <button>, no block elements inside <p>); the parser silently restructures violations.
- Default behaviour comes free: focusability, keyboard activation, form submission, link navigation,
<details> disclosure, <dialog> with showModal() (focus trapping and the top layer).
- Forms: every control has a
name and a <label>; group related controls with <fieldset>/<legend>; use the right type and autocomplete tokens; constraint validation (required, pattern, min, max, minlength) plus setCustomValidity; :user-invalid for styling; server-side validation regardless.
- Submission: GET puts fields in the query string; POST uses
application/x-www-form-urlencoded by default or multipart/form-data for files; FormData builds either from a form or by hand.
- Images:
alt, width/height for aspect ratio, srcset/sizes and <picture> for responsive and format choices, loading="lazy" below the fold, fetchpriority="high" for the hero.
- Loading: classic scripts block parsing;
defer and modules run after parsing in order; async on arrival; preload for late-discovered critical resources, modulepreload for module graphs, preconnect for early connections to other origins, prefetch for likely next navigations.
Numbers to remember
- Heading levels: 6. Landmarks a page should have: one
main, usually a header, nav and footer.
- CLS thresholds: good at most 0.1, poor above 0.25.
<meta name="viewport"> absent: mobile browsers assume a layout width of about 980 px.
Pitfalls
- Placeholders as labels; inputs without
name; inputs without type on phones (wrong keyboard).
- Clickable
divs and spans; links with href="../software-engineering/the-web-frontend/ch13.html#" used as buttons; buttons inside forms without type="button" that submit unexpectedly.
- Skipping heading levels for visual size; multiple
<h1>s used as styling.
- Missing
alt, or alt that repeats nearby text or says "image of".
- Setting
Content-Type manually on a FormData fetch (breaks the boundary).
- Lazy-loading the hero image.
- Treating client-side validation as security.
Glossary
- Void element: an element with no content or end tag (
img, input, br, meta, link).
- Landmark: a region role (banner, navigation, main, contentinfo) that assistive tech can jump between.
- Accessible name: the text a control is announced by (from its content, label,
alt, aria-label or aria-labelledby).
- Constraint validation API:
validity, validationMessage, checkValidity(), reportValidity(), setCustomValidity().
- Multipart boundary: the unique separator line between parts of a multipart body.
- Top layer: where modal dialogs and popovers render, above all other content regardless of z-index.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Forms always send UTF-8." |
They send the page's encoding, with &#NNNN; for characters it can't represent. |
| "Enter submits forms." |
Only with a submit button, or a single field. |
"type=number sends digits." |
It sends any valid floating-point string: 1e1, 05, 2.0. |
"maxlength counts characters." |
It counts UTF-16 code units; emoji count double, and names can be cut mid-syllable. |
"A <button> inside a form is just a button." |
Its default type is submit. Use type="button" for anything else. |
| "ARIA makes elements accessible." |
ARIA only changes what's announced; it adds no behaviour. Native elements first. |
14
Key ideas
- The cascade sorts competing declarations by: origin and importance → context (shadow DOM) →
style attribute → layers → specificity → order of appearance. Unlayered beats layered for normal declarations; the order reverses for !important.
- Specificity is (ids, classes/attributes/pseudo-classes, types/pseudo-elements);
:is()/:not()/:has() take their most specific argument, :where() counts zero, * counts zero.
- Inheritance: text properties inherit;
inherit, initial, unset, revert and revert-layer control it explicitly.
- Values go specified → computed → used → actual; custom properties are computed as tokens and substituted at
var() time; @property gives them types (and makes them animatable).
- Box model and
box-sizing; margin collapsing between blocks in normal flow; block formatting contexts (flow-root) contain floats and stop collapse.
- Layout modes: normal flow, flexbox (one dimension; grow/shrink/basis,
min-width: auto), grid (two dimensions; fr, minmax, auto-fill/auto-fit, named areas, subgrid), positioning (relative, absolute against the nearest positioned ancestor, fixed, sticky).
- Stacking contexts scope
z-index; created by positioned elements with a z-index, opacity < 1, transforms, filters, isolation: isolate, containment and more; the top layer sits above all of them.
- Responsive: mobile-first
min-width media queries, fluid units and clamp(), container queries for components, responsive images.
- Modern CSS: nesting,
:has(), logical properties (margin-inline), oklch() and color-mix(), scroll-driven animations, view transitions, prefers-reduced-motion, prefers-color-scheme.
Numbers to remember
- 1rem = 16px by default; 1 CSS px ≈ 1/96 inch at arm's length.
- Specificity examples:
#a (1,0,0) > .a .b (0,2,0) > a.b (0,1,1) > a (0,0,1).
- Typical mobile-first breakpoints: about 40rem (640px) and 64rem (1024px), but choose them from your content.
Pitfalls
- Fighting specificity with ids and
!important instead of layers or better structure.
- Forgetting
box-sizing: border-box, or min-width: 0 on flex items with long content.
- Expecting
z-index to escape a parent's stacking context.
height: 100vh on mobile (address bars); use 100dvh/svh.
- Styling with media queries when the component's container width is what matters.
- Removing focus outlines (
outline: none) without a visible replacement.
- Animating layout properties (
top, width) instead of transform and opacity (chapter 27).
Glossary
- Formatting context: the rules a box uses to lay out its children (block, inline, flex, grid).
- Containing block: the rectangle percentages and positioned offsets are measured against.
- Cascade layer: a named bucket (
@layer) with an explicit priority order.
- Custom property: a
--name value that cascades and inherits, read with var().
- Intrinsic size: the size content wants (
min-content, max-content, fit-content).
- Logical properties: direction-relative properties (
inline/block, start/end) that adapt to writing modes.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "The nearer ancestor's rule wins." |
Selectors ignore distance; only @scope and inheritance know nearness. |
"The hidden attribute always hides." |
It's a user-agent display: none, beaten by any author display. |
"1.5em and 1.5 are the same line height." |
Same on the element; different for every descendant with another font size. |
| "Invalid CSS is ignored, so an earlier declaration still applies." |
Only parse-time errors. A var() that turns out invalid makes the property unset. |
"outline: none is fine if I add a box-shadow ring." |
Forced-colours mode removes box-shadows; use a transparent outline. |
| "Higher specificity always wins." |
Only after origin, importance, context and layers have tied. |
| "Eleven classes beat an ID." |
Specificity columns never carry over. |
15
Key ideas
- Seven primitive types (number, bigint, string, boolean, undefined, null, symbol) plus objects; primitives are immutable and compared by value, objects by reference.
const by default, let when reassigning; block scope; the temporal dead zone; var is function-scoped and hoisted.
- Coercion:
==, + with strings, truthiness; use ===, explicit Number()/String(), ?? and ?..
- Functions are values; closures capture variables (not values) from their lexical scope; arrow functions take
this from their surroundings, ordinary functions from how they're called.
- Prototypes: property lookup walks the prototype chain;
class is syntax over prototypes with real private fields (#x).
- Event loop: run a task to completion → drain all microtasks → maybe render (rAF, style, layout, paint) → next task. Promises,
await and queueMicrotask are microtasks; timers, events and messages are tasks.
- Promises: pending → fulfilled or rejected, once;
then callbacks always run asynchronously; combinators all (fail fast), allSettled, race, any; cancel with AbortController/AbortSignal.timeout/AbortSignal.any.
fetch rejects only on network failure or abort; check response.ok.
- Iterators and generators power
for…of, spread and destructuring; async iterators power for await.
- Modules: static
import/export, live bindings, evaluated once, import() for lazy loading, top-level await.
- Built-ins worth knowing:
Map/Set (any keys, insertion order), WeakMap/WeakRef, typed arrays, structuredClone, Intl, Temporal (arriving in browsers; replaces Date's pitfalls).
Numbers to remember
- Safe integers: ±(2⁵³ − 1) = ±9,007,199,254,740,991.
- Long task: over 50 ms. A 60 Hz frame: about 16.7 ms.
setTimeout nesting clamp: at least 4 ms after five nested levels; background tabs throttle timers to once a second or less.
Pitfalls
==, string concatenation from form values, sort() without a comparator, parseInt without a radix or as a map callback.
this lost when passing a method as a callback (button.addEventListener("click", obj.method)).
- Awaiting independent work sequentially; forgetting
await (a promise is truthy); unhandled rejections.
- Race conditions from out-of-order responses; no timeouts on fetch.
- Mutating shared objects and arrays (
sort, reverse, splice mutate; toSorted, toReversed, with don't).
- Money in floating point; 64-bit IDs as numbers.
- Long synchronous loops on the main thread.
Glossary
- Coercion: implicit conversion between types.
- Closure: a function plus the variables it captured from its creation scope.
- Prototype chain: the linked objects searched for properties not found on an object itself.
- Microtask: a job run right after the current task, before rendering (promise reactions,
await continuations).
- Long task: a task that keeps the main thread busy for more than 50 ms.
- Live binding: an imported name that reflects the exporting module's current value.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
"(a, b) => a > b sorts ascending." |
It must return a negative number to move anything; a boolean leaves the array unsorted. |
"try/catch in an async function catches everything inside it." |
Not a promise returned without await. |
| "A closure keeps only the variables it uses." |
In V8, all closures from one scope share a context holding every variable any of them uses. |
| "Async code loses stack traces." |
await chains keep them; callbacks and timers don't. |
| "Circular imports are fine in ES modules." |
They work only if no module uses another's binding during evaluation; the result depends on load order. |
"structuredClone deep-copies anything." |
Not prototypes, functions, DOM nodes or class instances' methods. |
"async makes code run in parallel." |
It runs on the same thread; it only stops blocking while waiting for I/O. |
16
Key ideas
- TypeScript is a static checker over JavaScript; types are erased. Only
enum, namespace and parameter properties emit code; avoid them with erasableSyntaxOnly.
- Structural typing: compatibility is about shape; excess property checks catch typos in fresh literals; brands add nominal distinctions.
- Inference flows from values and context; annotate parameters, exported APIs and data models.
- Unions + narrowing (
typeof, instanceof, in, equality, discriminant fields, type predicates, assertion functions); exhaustiveness with never.
- Generics with constraints (
<T extends { id: string }>), defaults and inference; variance (in/out annotations) matters for function types.
- Type-level tools:
keyof, indexed access T[K], mapped types, conditional types with infer, template literal types, utility types (Partial, Pick, Omit, Record, ReturnType, Awaited).
satisfies checks a value against a type without widening it; as const keeps literal types.
- Unsound escapes:
any, as, non-null !, overloads, bivariant method parameters, index access without noUncheckedIndexedAccess.
- Boundaries: validate external data at run time (schemas) and derive types from the schema or a shared contract.
- Declarations:
.d.ts files, @types/*, module augmentation and declaration merging; module resolution bundler vs nodenext.
Numbers to remember
strict bundles about eight checks and is the default since TypeScript 6.0; add noUncheckedIndexedAccess and exactOptionalPropertyTypes deliberately.
- TypeScript 7.0 (2026) is the native Go compiler, reported at around 10× faster on large projects; 6.0 was the last JavaScript-based release.
- Node runs
.ts with type stripping (flag in 22, default from 23.6).
Pitfalls
as on API responses; any from JSON.parse leaking through the app.
- Non-null assertions (
el!) instead of handling the null case.
enum with type stripping; numeric enums accepting any number.
- Optional properties vs
| undefined (they differ under exactOptionalPropertyTypes).
- Over-engineered type-level code that slows the checker and confuses readers.
- Assuming
readonly or private (private keyword) is enforced at run time; use #private for that.
Glossary
- Assignability: whether a value of one type may be used where another is expected.
- Type predicate: a return type
x is T that narrows when the function returns true.
- Discriminant: the literal-typed property that tells union members apart.
- Widening: inference choosing
string instead of "ready" for mutable bindings.
- Declaration file: a
.d.ts file describing types for JavaScript code.
- Type stripping: running TypeScript by deleting type syntax without checking it.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Narrowing is reset whenever the value could change." |
In callbacks, yes; across await and function calls, no. |
"readonly makes a property immutable." |
Only through that type; an alias with a mutable type can write it. |
| "The type system can model any set of strings." |
Unions are capped at 100,000 members, and large ones slow every check. |
"skipLibCheck only skips node_modules." |
It skips every .d.ts, and broken declarations become any. |
"Omit<T, 'x'> checks that x exists." |
Omit accepts any key, so typos compile; Pick checks. |
| "Typed JSON is checked JSON." |
JSON.parse returns any; nothing checks it unless you do. |
17
Key ideas
- The DOM is a tree of
Nodes (elements, text, comments) under a Document; query with CSS selectors (querySelector, closest, matches); live HTMLCollections vs static NodeLists.
- Change content with
textContent, properties, classList, dataset, append/replaceChildren; build with createElement, <template> cloning or fragments; innerHTML only for trusted or sanitised HTML.
- Events: capture → target → bubble;
preventDefault vs stopPropagation; passive listeners for scroll and touch; AbortSignal to remove many listeners at once ({ signal }); delegation with closest().
- Rendering cost: DOM writes are cheap until something reads geometry; interleaving reads and writes forces synchronous layout (thrashing); batch reads, then writes.
- Observers:
MutationObserver (microtask, batched), IntersectionObserver and ResizeObserver (async, tied to rendering), PerformanceObserver (performance entries).
- Networking APIs:
fetch with streams and AbortSignal; WebSocket for bidirectional messages; EventSource (SSE) for server push over HTTP; BroadcastChannel between same-origin tabs.
- Storage and files: IndexedDB, Cache Storage, OPFS;
File/Blob/URL.createObjectURL; the File System Access API (Chromium) for real files.
- Other APIs: Clipboard (async, permission-gated), Web Crypto (
subtle in secure contexts, randomUUID), Notifications and Push (via service workers), the History and Navigation APIs.
Numbers to remember
- Forced layouts in a loop: about 30× slower than batched in this chapter's lab (500 boxes: 55 ms vs 2 ms).
- A frame at 60 Hz: 16.7 ms; DOM work per frame should leave room for style, layout and paint.
- Practical DOM size: Lighthouse warns above about 1,400 elements; thousands of rows need virtualisation.
Pitfalls
innerHTML, outerHTML, insertAdjacentHTML and document.write with untrusted strings (XSS).
- Listeners added in loops and never removed (leaks in single-page apps); anonymous listeners that can't be removed (use
AbortController).
- Listening to
click on submit buttons instead of submit on forms; forgetting type="button".
- Reading layout in scroll handlers instead of using
IntersectionObserver.
- Querying the DOM for application state instead of keeping state in data structures.
- Using
keypress (deprecated) or keyCode instead of keydown and event.key.
Glossary
- Event delegation: handling events from many children with one listener on an ancestor.
- Default action: what the browser does after dispatch unless prevented (follow a link, submit a form, scroll).
- Forced synchronous layout: layout computed immediately because script read geometry after a change.
- Live collection: a collection that updates as the DOM changes (
getElementsByTagName, children).
- Retargeting: events from inside a shadow tree appearing to come from its host element.
- Trusted Types: a browser mechanism that blocks string assignments to dangerous DOM sinks unless they come from an approved policy.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Each tab has its own connections." |
Six HTTP/1.1 connections per origin are shared by all tabs in a browser profile. |
"EventSource always reconnects." |
Not after an HTTP error or a wrong content type: it closes for good. |
| "Reconnecting clients spread out naturally." |
They reconnect after the same fixed delay, all at once. |
"Date.now() is the time." |
It's the device's clock, which may be minutes off. |
"Every SSE library behaves like EventSource." |
Libraries differ in retrying, back-off, and even in what counts as a message. |
18
Key ideas
- URL → DNS → connection (TCP/QUIC) → TLS → HTTP → response → parse → DOM/CSSOM → style → layout → paint → composite; HSTS, the bfcache, service workers and speculation rules can short-circuit the start.
- Processes: browser, network, GPU, storage, utility, and sandboxed renderers; IPC to the browser process for anything privileged; site isolation gives each site its own renderer, including out-of-process iframes.
- Parsing: the tokenizer and tree builder build the DOM incrementally; the preload scanner fetches markup-discoverable resources early; CSS is render-blocking and blocks scripts that follow it.
- Style: selector matching with invalidation sets; cost scales with affected elements; layout (LayoutNG) computes geometry with fragment trees; paint records display lists; raster and composite run off the main thread on the GPU.
- Invalidation: geometry changes → layout + paint; visual changes → paint; transform/opacity on a composited layer → composite only; forced synchronous layout when script reads geometry after a write.
- Layers: promoted for transforms, opacity animations, video, canvas,
will-change, fixed elements; too many cost memory (layer explosion).
- Frames: vsync-driven; the main thread must finish its part within the budget; the compositor can scroll and run transform/opacity animations independently.
- JS engines: tiered (V8: Ignition, Sparkplug, Maglev, TurboFan), speculative, deoptimising; generational concurrent GC; Oilpan for DOM objects.
- Skipping work: CSS containment,
content-visibility: auto with contain-intrinsic-size, small DOMs.
Numbers to remember
- Frame budget: 16.7 ms at 60 Hz, 8.3 ms at 120 Hz; long task over 50 ms.
- In the lab: restyling 20,000 elements ≈ 73 ms;
content-visibility: auto cut initial layout from 75 ms to 5 ms.
- Site isolation memory overhead: roughly 10–20%.
Pitfalls
- Animating
top/left/width/height instead of transform; starting transforms from none mid-animation.
- Toggling classes high in the tree for small visual changes on huge DOMs.
- Hero images as CSS backgrounds or JS-inserted elements (invisible to the preload scanner).
will-change on everything (memory, layer explosion); leaving it on after the animation.
- Detached DOM trees kept alive by listeners or caches.
- Profiling only on a fast laptop; use CPU throttling and real mid-range phones.
Glossary
- Main thread: the renderer thread running JavaScript, style, layout and paint recording.
- Compositor thread: the thread that assembles layers into frames and handles scrolling.
- Invalidation: marking work that must be redone after a change.
- Out-of-process iframe (OOPIF): a cross-site frame rendered by a different renderer process.
- Preload scanner: a look-ahead parser that discovers and requests resources early.
- Deoptimisation: discarding speculative optimised code when its assumptions fail.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
"font-display: swap is the safe default." |
It shows text early and shifts the layout when the font arrives. |
"size-adjust on the web font fixes font shifts." |
It belongs on a local fallback face, with overrides divided by the adjustment. |
| "Selector cost is about matching speed." |
It's about how much a change invalidates; a :has() on a changing class reaches the whole page. |
| "Speculation rules are just markup." |
Inline rules are script for CSP; use the header under a strict policy. |
| "CLS adds up every shift." |
It's the worst burst (session window) of shifts. |
| "Fast servers mean fast pages." |
Most load time is in the browser: parsing, fonts, images, scripts and rendering. |
19
Key ideas
- HTTP semantics (methods, status codes, headers, content negotiation, caching, conditional requests) are the same across versions; the versions differ in framing and transport.
- HTTP/1.1: text, one outstanding request per connection, about six connections per host. HTTP/2: binary frames, multiplexed streams, HPACK header compression, one TCP connection (TCP head-of-line blocking under loss). HTTP/3: QUIC over UDP, per-stream loss recovery, 1-RTT (0-RTT resumption) handshakes, connection migration; advertised with
Alt-Svc or DNS HTTPS records.
- Caching: freshness (
max-age, s-maxage, immutable) then validation (ETag/If-None-Match, Last-Modified/If-Modified-Since → 304); no-cache revalidates, no-store never stores; Vary splits cache entries; stale-while-revalidate serves stale while refreshing. Hash static file names and cache them for a year.
- Compression: negotiated via
Accept-Encoding/Content-Encoding; precompress static assets with Brotli 11; fast levels for dynamic content.
- Cookies:
Domain, Path, Expires/Max-Age, Secure, HttpOnly, SameSite (Lax default), Partitioned (CHIPS); __Host- prefix for locked-down session cookies.
- CORS: the server opts in with
Access-Control-Allow-Origin; non-simple requests are preflighted (OPTIONS, cached by Access-Control-Max-Age); credentials require an exact origin plus Allow-Credentials: true; Access-Control-Expose-Headers for reading custom response headers.
- Real time: polling, long polling, SSE (auto-reconnect,
Last-Event-ID), WebSocket (bidirectional, you build reconnection), WebTransport (streams and datagrams over HTTP/3).
Numbers to remember
- 6 connections per host on HTTP/1.1 (24 × 500 ms requests: 2,044 ms vs 560 ms on HTTP/2 in the lab).
- Cookie size about 4 KB; preflight cache capped at 2 hours in Chromium (
Access-Control-Max-Age).
- Brotli 11 on a 625 KB bundle: 14.3% of original vs gzip's 17.8%.
- One year =
max-age=31536000.
Pitfalls
- Treating CORS as server security; fixing CORS errors in frontend code.
Access-Control-Allow-Origin: * with credentials; reflecting any Origin back with credentials allowed (a vulnerability).
no-cache without ETag/Last-Modified; caching HTML for long periods; forgetting Vary: Accept-Encoding or Vary: Origin at CDNs.
- Session cookies without
HttpOnly, Secure and a SameSite choice.
- Assuming
fetch rejects on HTTP errors; no timeouts or retries with backoff.
- WebSockets without heartbeats, reconnection and resume.
Glossary
- Idempotent: repeating the request has the same effect as doing it once (GET, PUT, DELETE).
- Validator: an
ETag or Last-Modified value used for conditional requests.
- Preflight: the
OPTIONS request asking permission for a non-simple cross-origin request.
- Multiplexing: interleaving many requests' frames on one connection.
- Head-of-line blocking: a lost or slow item delaying everything queued behind it.
- SameSite: a cookie attribute controlling whether it's sent with cross-site requests.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
"A cancelled fetch rejects with AbortError." |
It rejects with the signal's reason: TimeoutError, your own error, or AbortError only without a reason. |
"sendBeacon always sends." |
It returns false past 64 KiB of in-flight keepalive data, shared across the page. |
| "My code sees 304s." |
The browser hides them unless you set the conditional header yourself, and then the body is empty. |
| "Retry libraries make requests safe to repeat." |
They only retry methods assumed idempotent; POST needs a key. |
| "Exponential back-off spreads retries out." |
Without jitter, everyone backs off by the same amounts and returns together. |
| "CORS protects my API." |
It protects users' browsers; any non-browser client ignores it. |
20
Key ideas
- Accessibility serves permanent, temporary and situational disabilities; WCAG 2.2 AA is the usual legal and contractual target; POUR organises its criteria.
- Semantic HTML first: native elements bring roles, names, states, focusability and keyboard behaviour; ARIA only changes semantics, never behaviour.
- Accessible name computation:
aria-labelledby > aria-label > native label (<label>, alt, <caption>, <legend>) > content > title/placeholder; descriptions via aria-describedby.
- Keyboard: everything operable with Tab/Shift+Tab, Enter, Space, arrows and Escape; logical focus order; visible
:focus-visible; no keyboard traps; roving tabindex inside composite widgets.
- Focus management in SPAs: move focus to new content or the main heading after navigation; return focus when dialogs close;
inert for background content.
- Live regions (
aria-live="polite", role="status", role="alert") announce dynamic updates; the region must exist before its content changes.
- Visual: contrast 4.5:1 text, 3:1 large text and UI components; reflow at 320 CSS px; text spacing; don't rely on colour alone;
prefers-reduced-motion; target size at least 24 × 24 CSS px (WCAG 2.2).
- Widget patterns from the ARIA Authoring Practices Guide: dialog, tabs, menu button, combobox, tree, grid, accordion, tooltip.
- Testing: automated (axe, Lighthouse) in CI + keyboard + zoom + screen readers (NVDA, JAWS, VoiceOver, TalkBack) + users with disabilities.
Numbers to remember
- 1 in 6 people live with a significant disability (WHO).
- Contrast: 4.5:1 normal text, 3:1 large text (24 px, or 18.66 px bold) and UI components;
#767676 on white = 4.54:1.
- Reflow at 320 CSS px (400% zoom of 1280 px); text resizable to 200%.
- Target size minimum 24 × 24 CSS px (AA, WCAG 2.2); 44 × 44 recommended.
Pitfalls
- Clickable
divs, href="../software-engineering/the-web-frontend/ch20.html#" buttons, icon-only controls without names.
- Removing outlines; focus hidden behind sticky headers (WCAG 2.2 "focus not obscured").
- Placeholder-only labels; error messages not tied to fields (
aria-describedby, aria-invalid).
aria-label that contradicts visible text (breaks voice control); redundant or wrong roles.
- Live regions inserted along with their content (not announced).
- SPA route changes that leave focus on a removed element.
- Believing a zero-violation automated report means accessible.
Glossary
- Accessible name: what assistive technology announces for an element.
- Accessibility tree: the browser's semantic tree exposed to platform accessibility APIs.
- Landmark: a page region role (banner, navigation, main, complementary, contentinfo, search, form, region).
- Inert: content that can't be focused, clicked or found by assistive tech.
- Roving tabindex: one tab stop per widget, with arrow keys moving within it.
- VPAT / ACR: a vendor's accessibility conformance report against WCAG.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Performance CSS doesn't affect accessibility." |
content-visibility: auto leaves off-screen content out of Chromium's tree. |
| "Decorative CSS content is ignored by screen readers." |
It's part of the name unless given an empty alternative (content: "→" / ""). |
| "Disabling a button during a request is harmless." |
It drops keyboard focus; use aria-disabled and ignore repeat clicks. |
| "Our tests check names, so they match the browser." |
Test libraries compute names themselves and can disagree with the browser. |
| "An aria snapshot is the accessibility tree." |
Playwright's snapshot is computed from the DOM; the browser's tree can differ. |
| "Accessibility overlays fix compliance." |
They don't fix the underlying markup and often interfere with users' own tools. |
21
Key ideas
- UI = f(state): keep state in data structures and derive the screen; never use the DOM as the source of truth.
- Components take props and render UI; data flows down, events flow up through callbacks; state lives at the lowest common owner.
- Boundaries: one reason to change; props as the contract; containers (data) vs presentational (display) where it helps.
- Patterns: composition over configuration; slots/children; compound components sharing implicit state (
<Tabs><Tabs.List/><Tabs.Panel/></Tabs>); headless components that provide behaviour and accessibility without styles (Radix, React Aria, Headless UI, Angular CDK).
- Design systems: tokens (colour, space, type, radius, motion) → primitives → patterns → guidelines; versioned and documented (Storybook); accessibility built in.
- Sync strategies: rebuild (loses state), virtual DOM diff (work ∝ re-rendered subtree), signals (work ∝ changed bindings), compilers (decided at build time); stable keys for lists.
- Web Components: custom elements, shadow DOM (style and query encapsulation, event retargeting), slots, parts, custom properties; Declarative Shadow DOM for SSR;
ElementInternals for forms.
- Code organisation: by feature; public
index per feature; dependency direction app → features → shared; enforce with lint rules.
- Trade-offs: reuse vs coupling; the cost of abstraction; the rule of three before extracting; prefer duplication over the wrong abstraction.
Numbers to remember
- Lab: one change in a 1,000-item list touched 2,004 nodes by rebuilding, 1 by diffing (1,000 comparisons) or by signals (1 effect).
- Rule of three: extract a shared abstraction on the third real use, not the first.
Pitfalls
- Duplicated state (the same fact stored twice and drifting); derived data stored instead of computed.
- Prop drilling through many layers instead of composition or context.
- Index keys in dynamic lists.
- "God" components and "util" dumping grounds; shared code importing features.
- Premature abstraction: configurable components with dozens of boolean props.
- Design-system forks: copying components instead of contributing changes back.
Glossary
- Props: inputs a component receives from its parent.
- Lifting state: moving state up to the nearest common ancestor of the components that need it.
- Reconciliation: matching a new UI description to existing DOM nodes and applying differences.
- Signal: a reactive value whose readers are tracked and re-run when it changes.
- Headless component: behaviour and accessibility without markup or styles opinions.
- Shadow root: the private DOM subtree attached to a custom element.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "A few booleans are simpler than a state machine." |
They allow combinations nobody designed; a machine allows only the states you list. |
| "i18n is translating strings." |
Plurals, number grouping, dates and direction need a formatting layer, not concatenation. |
| "Full-page screenshots catch visual regressions." |
Any shift floods the diff; test components in isolation. |
| "Signals re-run only what changed." |
They re-run what depends on a value that's no longer ===; a computed array is new every time. |
| "Shared code should be extracted early." |
Extract at the third use, when the shape is known. |
| "Micro-frontends fix team coupling." |
They move it to runtime contracts and duplicate frameworks; they solve an organisational problem at a technical cost. |
22
Key ideas
- Components are functions of props and state returning JSX (compiled to
jsx() calls); rendering must be pure; side effects go in event handlers or effects.
- State:
useState/useReducer; updates are immutable and batched; state is a per-render snapshot; updater functions for values derived from the previous state; derive instead of duplicating.
- Effects synchronise with external systems after commit; dependency arrays; cleanups; Strict Mode's double-invoke in development; "you might not need an effect" for derived data and event-driven logic.
- Refs (
useRef) for mutable values that don't trigger renders and for DOM access; context for values many components need (theme, user), not as a general store.
- Rendering pipeline: trigger → render (call components, build the new tree) → reconcile (Fiber diff with keys) → commit (DOM mutations, layout effects, then passive effects); a parent render re-renders its subtree unless memoised.
- Concurrent features: transitions and
useDeferredValue make updates interruptible; Suspense shows fallbacks while code or data loads; streaming SSR and selective hydration.
- Server Components (RSC) render on the server and send a serialised tree;
"use client" marks the client boundary; Server Functions ("use server") and Actions (useActionState, useOptimistic, form action) handle mutations.
- React Compiler auto-memoises components and hooks at build time.
Numbers to remember
- Lab: 4 keystrokes re-rendered 400 unmemoised children vs 0 memoised; deferred rendering cut keystroke latency from about 160 ms to about 15 ms.
- Strict Mode in development: effects run, clean up, and run again once on mount.
Pitfalls
- Mutating state; stale closures in handlers, effects and intervals; missing or index keys.
- Effects for derived state or event logic; missing dependencies (lint with
react-hooks/exhaustive-deps); fetch races without cleanup.
- New object/function props defeating
memo (absent the compiler); context values recreated each render causing app-wide re-renders.
- Hydration mismatches (dates, random ids,
window checks during render); use useId for ids.
- Putting server-only secrets in client components; serialising huge props across the RSC boundary.
Glossary
- Reconciliation: comparing the new element tree with the previous one to compute DOM changes.
- Fiber: React's internal unit of work and data structure enabling interruptible rendering.
- Commit: the phase where React applies changes to the DOM and runs layout effects.
- Transition: a state update marked non-urgent and interruptible.
- Hydration: attaching React to server-rendered HTML so it becomes interactive.
- Client boundary: the
"use client" module where the server component tree hands over to client components.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "React output is XSS-safe." |
Text and attributes are escaped; raw HTML, inline JSON and URLs are yours to handle. |
| "Wrap it in startTransition and it won't block." |
Only updates to React state are interruptible; store updates render synchronously. |
"useSyncExternalStore is just useEffect plus useState." |
That's the old shim, and it can commit inconsistent values; the built-in hook prevents tearing. |
"memo makes a list cheap." |
Only if props stay ===; one prop that changes for every row re-renders every row. |
| "getSnapshot can build an object each time." |
It must return the same value while nothing changed, or React loops. |
| "Strict Mode's double effects are a development quirk." |
They rehearse what production remounts do; an effect without cleanup leaks there too. |
23
Key ideas
- Standalone components (class + decorator + template),
imports per component; templates compiled ahead of time (Ivy) into instructions and type-checked (strictTemplates, default since v22).
- Bindings:
{{ }}, [prop], (event), [(model)]; built-in control flow @if/@for (with track)/@switch/@defer; pipes for display transforms.
- Signals:
signal, computed (lazy, cached), effect, linkedSignal; signal-based input(), output(), model(), queries; resource/httpResource for async data (stable since v22).
- Change detection: OnPush by default since v22 (old behaviour renamed
Eager); zoneless by default since v21: views update after signal writes, events, async pipe emissions or markForCheck().
- Dependency injection:
inject(), providedIn: "root", environment and element injector hierarchy, InjectionTokens, providers for testing.
- Router: lazy
loadComponent/loadChildren, functional guards and resolvers, route-level providers, input binding from route params.
- Forms: Signal Forms (stable since v22) and reactive forms; validators; typed forms.
- HTTP:
HttpClient (fetch-based by default since v22), interceptors, httpResource.
- RxJS for event streams:
switchMap, mergeMap, concatMap, exhaustMap, debounceTime; takeUntilDestroyed; toSignal/toObservable.
- SSR: hydration, event replay, incremental hydration (default since v22) with
@defer (hydrate on …).
Numbers to remember
- A major release every 6 months; each supported 18 months (6 active + 12 LTS).
- Angular 22: TypeScript 6 and Node 22+ required.
Pitfalls
- Mutating arrays and objects held in signals (inconsistent views, as in the lab).
- Plain fields changed outside events in zoneless apps; reading the DOM before
whenStable() in tests.
effect used to derive state (use computed or linkedSignal).
- Manual
subscribe without takeUntilDestroyed (leaks); nested subscribes instead of flattening operators.
- Providing a service in a component when you meant a singleton (or vice versa).
- Huge shared modules or barrel files defeating lazy loading.
Glossary
- Decorator: an annotation (
@Component, @Injectable) that attaches metadata to a class.
- Injector: the container that creates and supplies service instances.
- Zoneless: change detection scheduled by signals and events instead of Zone.js patching async APIs.
- Type-check block: generated TypeScript the compiler uses to check a template.
- Flattening operator: an RxJS operator that maps each value to an inner Observable and merges the results under a concurrency policy.
@defer block: a template section whose code is lazy-loaded on a trigger (viewport, interaction, idle).
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Angular sanitises styles." |
Not since version 10; the browser rejects script in CSS, and the CSP does the rest. |
| "If the component renders, its styles work." |
Under a strict CSP, component styles are refused unless they carry the page's nonce. |
"esbuild is what ng build does." |
Angular's builder adds optimisations that made the bundle 3.4× smaller. |
"inject() works anywhere in a component." |
Only in an injection context: construction, factories, or runInInjectionContext. |
| "An effect that writes its own input will error." |
In Angular 22 it hung the tab, in production and development builds. |
| "OnPush plus signals makes inputs free." |
Each new object input marks its component for refresh; a tick cost 5× more. |
24
Key ideas
- Rendering strategies: CSR, SSR, SSG, ISR/revalidation, streaming SSR, partial prerendering (static shell + dynamic holes), islands, Server Components, edge rendering; choose per route.
- Hydration re-runs components in the browser to attach behaviour; it costs the full JavaScript of every hydrated component; mismatches force client re-rendering.
- Reducing hydration: islands (Astro), resumability (Qwik), incremental/partial hydration (Angular
@defer (hydrate on …)), Server Components (only client components ship JS).
- React Server Components: run on the server only, can read data directly, render to a serialised payload;
"use client" marks interactive leaves; props crossing the boundary must be serialisable; Server Functions ("use server") for mutations.
- Data loading: route loaders (React Router, SvelteKit, Nuxt), async Server Components (Next.js); avoid request waterfalls by starting queries in parallel and loading at the route level.
- Caching layers: browser, CDN, framework data cache, full-page cache; revalidate by time or by tag/path; Next.js 16's explicit
"use cache" with cacheLife/cacheTag.
- Runtimes: Node.js servers, serverless functions, edge isolates (fast start, limited APIs, near users but often far from databases).
- Framework landscape: Next.js (React, RSC-first), React Router v7 framework mode (formerly Remix), Astro (content, islands, any UI library), SvelteKit, Nuxt (Vue), Angular SSR, TanStack Start, Qwik City.
Numbers to remember
- Lab (throttled phone): menu visible CSR 1.68 s, SSR 0.43 s, SSG 0.11 s; button usable after about 1.4–1.7 s for all hydrated variants vs 0.13 s for an island.
- Streaming: first chunk at 34 ms vs 800 ms waiting for the slow section.
Pitfalls
- Treating SSR as a fix for slow interactivity; shipping the whole app's JS to hydrate mostly static pages.
- Hydration mismatches from dates, randomness,
window checks, invalid HTML nesting and extensions.
- Data waterfalls (parent fetches, then child fetches); fetching in effects after hydration what the server already had.
- Caching personalised responses at a CDN; forgetting cache invalidation on writes.
- Putting secrets or heavy server-only code where it can be bundled for the client; leaking data through serialised props.
- Edge functions calling a database on another continent (each query pays the distance).
Glossary
- TTFB: time to first byte of the response.
- Hydration: attaching client behaviour to server-rendered HTML.
- Island: an independently hydrated interactive component in an otherwise static page.
- Resumability: continuing the server's execution state in the browser without re-running components.
- Revalidation: regenerating cached/static output after a time or an event.
- Suspense boundary: a component boundary that shows a fallback until its contents are ready, and a streaming unit.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "SSR makes pages faster." |
It makes content visible sooner; total main-thread work went up. |
| "Hydration is cheaper than rendering." |
It took as long as rendering from nothing here. |
| "Compression breaks streaming." |
Only where a layer doesn't pass flush() through. |
"JSON.stringify is fine for embedding state." |
It loses types and doesn't escape </script>. |
| "A slow data source just makes the page slow." |
Without a deadline the response never ended. |
| "Development and production SSR send the same HTML." |
Development put the server's error message and file paths in the page. |
25
Key ideas
- Classify first: UI, form, shared client, server, URL and persistent state each have a natural home; ask who owns the truth.
- Local by default, lift to the nearest common owner, share widely only when needed; never store derived data.
- Context is dependency injection for values, not a performance-aware store: every consumer re-renders on value change; split contexts; keep values stable.
- Stores: Redux Toolkit (actions, reducers, slices, middleware, DevTools), Zustand (minimal store with selectors), Jotai/Recoil-style atoms, signals (Angular, Solid, Preact, Vue refs), MobX observables; selectors limit re-renders.
- Reducers and events: pure
(state, action) → state; action logs enable testing, replay, undo and debugging.
- State machines and statecharts (XState) make impossible states unrepresentable; discriminated unions do the same in types.
- Server state: a cache keyed by query keys; dedupe, staleness (
staleTime), garbage collection (gcTime), background refetch, invalidation after mutations, optimistic updates with rollback, pagination and infinite queries, retries with backoff, cancellation.
- URL state for anything shareable; persistence with care (versioning, migrations, eviction).
- Local-first and sync engines (Replicache/Zero, ElectricSQL, Triplit, CRDTs like Yjs/Automerge) keep a local database that syncs with the server.
Numbers to remember
- Lab: one context change re-rendered all 3 consumers; selectors re-rendered 1.
- TanStack Query defaults:
staleTime 0, gcTime 5 minutes, queries retry 3 times, mutations 0.
- 3 booleans = 8 combinations for 4 valid states.
Pitfalls
- A single global context for everything; inline context values.
- Copying server data into client stores; fetching in effects without cancellation or caching.
- Storing derived or duplicated data; normalising too late (the same entity in two places, edited in one).
- Optimistic updates without rollback or visible errors; optimistic updates for irreversible actions.
- Putting shareable view state (filters, tabs) in memory instead of the URL.
- Boolean flag soup for async status.
Glossary
- Selector: a function picking the slice of state a component depends on.
- Query key: the identity of a cached server resource (
["dish", id]).
- Stale-while-revalidate: show cached data immediately while refetching in the background.
- Optimistic update: applying an expected server change locally before confirmation.
- Normalisation: storing entities once by id and referencing them elsewhere.
- CRDT: a conflict-free replicated data type that merges concurrent edits deterministically.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
"localStorage is always there." |
It threw on read in a sandboxed frame and on write at 5 MiB. |
| "The storage event keeps all tabs in sync." |
It fired in the other tab, not the one that wrote. |
| "Put filters in the URL and you're done." |
Push or replace is a decision; controls must follow Back. |
| "Dark mode from localStorage is fine with a fast script." |
A module script let one wrong frame through. |
| "Stores only notify when something changed." |
Zustand's merge notified for an unchanged value. |
| "Classifying state is a one-off exercise." |
Each new feature adds state to place; the build's filter and theme were both new kinds. |
26
Key ideas
- Tests buy the confidence to change code; test behaviour through public interfaces, not implementation details.
- Levels: unit (pure logic), component/integration (rendered UI with mocked boundaries), E2E (real app, real browser); one test per behaviour at the cheapest level that can catch its bugs; the "trophy" weights integration tests.
- Testing Library queries by role, label and text (
getBy, queryBy, findBy); user-event for realistic interaction; jest-dom matchers.
- Test doubles: stubs, mocks, fakes, spies; mock at boundaries (network with MSW, time with fake timers), not internal modules.
- E2E with Playwright: locators by role, auto-waiting assertions, fixtures,
page.route() for network control, traces, parallel workers, multiple browsers.
- Reliability: no fixed sleeps; isolate tests (reset handlers, storage, databases); deterministic data and clocks; retries only as a last resort and tracked.
- Quality of the suite: coverage shows what ran; mutation score shows what would be caught.
- Specialised: visual regression (screenshot diffs), accessibility (axe in component and E2E tests), performance budgets (Lighthouse CI), contract tests against API schemas (OpenAPI, Pact).
Numbers to remember
- Lab: unit tests about 1 ms each; component tests tens to hundreds of ms plus about 1 s jsdom start-up per file; an E2E run about 3 s.
- Lab: a 200 ms fixed wait failed 22/40 runs; auto-waiting failed 0/40.
- Lab: 80% line coverage; 2 of 7 mutants survived, one of them on a fully covered line.
Pitfalls
- Testing implementation details (state values, class names, internal calls); snapshot tests of entire components that everyone updates blindly.
getBy for async content; fixed setTimeout/waitForTimeout waits; shared state between tests.
- Over-mocking (mocking the module under test's collaborators until nothing real is tested).
- Too many E2E tests for logic that unit tests could cover; no E2E test for the money path.
- Ignoring flaky tests instead of fixing or quarantining them.
- Chasing a coverage percentage rather than meaningful assertions.
Glossary
- Assertion: a check that fails the test when false.
- Test double: any stand-in for a real dependency (stub, mock, fake, spy).
- Flaky test: a test that passes and fails without code changes.
- Auto-waiting: retrying an action or assertion until the page is ready or a timeout passes.
- Mutant: a deliberately altered version of the code used to check that tests catch changes.
- Trace: a recorded timeline of a test run (actions, network, DOM snapshots) for debugging.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "jsdom is a lightweight browser." |
No layout, no @layer, no resolved custom properties. |
| "axe passing means the page is accessible." |
axe was identical before and after fixing focus and invalid state. |
| "More generated cases make a stronger test." |
20,000 sequences killed 4 of 15 mutants. |
| "Visual tests are too flaky to be strict." |
Zero tolerance held across six runs once data and anti-aliasing were controlled. |
| "Two components that look the same render the same." |
Three text nodes instead of one changed 71 pixels. |
| "Unreachable inputs don't need tests." |
The snapshot bug needed an input the server never sends, until it does. |
27
Key ideas
- Core Web Vitals at p75 of real users: LCP (loading), INP (responsiveness), CLS (visual stability); supporting TTFB, FCP, TBT (lab proxy for INP).
- LCP = TTFB + resource load delay + resource load time + element render delay; fix the largest phase: server and caching, discoverability and priority (preload,
fetchpriority, no lazy hero), bytes (responsive modern images), render-blocking resources.
- INP = input delay + processing + presentation; yield (
scheduler.yield()), update UI first, debounce, move work to workers, keep the DOM small, avoid layout thrashing.
- CLS: reserve space (dimensions,
aspect-ratio, min-heights), no content inserted above, font-display with metric overrides, animate transforms.
- JavaScript cost: download + parse + compile + execute; budgets; code splitting by route and interaction; tree shaking (ES modules,
sideEffects); prefetching likely next code; audit dependencies.
- Assets: AVIF/WebP,
srcset/sizes, CDN image resizing; fonts (WOFF2, subsetting, preload, font-display: swap/optional); HTTP caching with hashed files.
- Runtime: virtualise long lists,
content-visibility, avoid leaks (cleanups, AbortController), memory profiling.
- Tools: Lighthouse, DevTools Performance (with throttling), WebPageTest, CrUX/PageSpeed Insights, RUM with
web-vitals, Lighthouse CI budgets.
Numbers to remember
- LCP ≤ 2.5 s good, > 4 s poor; INP ≤ 200 ms good, > 500 ms poor; CLS ≤ 0.1 good, > 0.25 poor.
- Long task > 50 ms; frame 16.7 ms.
- Lab: an 11.8 MB hero PNG → 88 KB WebP took LCP from 10.9 s to 0.17 s; splitting a 663 KB library made the page ready 7× sooner.
Pitfalls
- Optimising lab scores while field data stays poor (or the reverse); testing only on fast laptops.
- Lazy-loading the LCP image; hero images in CSS backgrounds; carousels as the first screen.
- Third-party scripts (tags, chat widgets, A/B testing) loaded synchronously.
- Lazy-loading code without prefetching, moving the delay to the user's first click.
- Huge client bundles hidden by fast networks in development.
- Listeners, intervals and subscriptions without cleanup in SPAs.
Glossary
- Critical rendering path: the resources and steps needed before the first render.
- Render-blocking resource: CSS or synchronous script that delays rendering.
- Field data / RUM: measurements from real user sessions.
- Performance budget: an agreed limit (bytes, LCP, INP) enforced in CI.
- Tree shaking: removing unused exports at build time.
- Detached DOM: nodes removed from the document but still referenced from JavaScript.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Good INP means a responsive app." |
INP stopped at 40–64 ms; the result took 42–204 ms. |
| "4× throttling shows a 4× slower device." |
One view got 2.1× slower; long tasks appeared from nothing. |
| "A budget test catches regressions." |
Only large ones; a 20 ms change needs about 70 runs per side. |
| "INP is the worst interaction." |
It's an estimated 98th percentile, from at most ten candidates. |
| "No long tasks means no jank." |
Chunks just under 50 ms still fill frames (stage 23's 44–48 ms passes). |
| "Fallbacks are free." |
A newly available feature without one cost the whole palette. |
28
Key ideas
- Threat model: hostile content and links, malicious sites in other tabs, compromised dependencies, stolen tokens; the server must enforce everything that matters.
- XSS: reflected, stored, DOM-based; sources (URL, storage,
postMessage, API data) flowing into sinks (innerHTML, href, eval, script src); framework escaping and its escape hatches; sanitise with DOMPurify or setHTML().
- CSP: strict nonce/hash-based
script-src with 'strict-dynamic', object-src 'none', base-uri 'none', frame-ancestors, report-only rollout and reporting.
- Trusted Types: only policy-produced values reach DOM XSS sinks; restrict allowed policy names.
- CSRF: SameSite cookies (Lax default), CSRF tokens,
Origin/Sec-Fetch-Site checks, no state changes on GET.
- Clickjacking:
frame-ancestors; cross-origin isolation: COOP, COEP, CORP; HSTS with preload.
- Prototype pollution: unsafe merges and path setters;
__proto__ keys; null-prototype objects and Map; schema validation.
- Auth in browsers: OAuth 2.0 authorization code + PKCE, OIDC ID tokens, BFF pattern keeping tokens server-side,
HttpOnly session cookies, short-lived access tokens with refresh rotation, passkeys (WebAuthn).
- Supply chain: lockfiles with integrity, automated updates,
npm audit/signatures and provenance, SRI for third-party scripts, minimal dependencies, least-privilege CI tokens.
Numbers to remember
- Lab: one
innerHTML line leaked a cookie and a token; textContent or a strict CSP stopped it.
- Lab: 31 advisories on two old dependencies.
- HSTS preload requires
max-age of at least one year (31536000) with includeSubDomains.
Pitfalls
- Static CSP nonces;
'unsafe-inline' with allow-list policies; CSP added only as a meta tag (no frame-ancestors or reporting there).
- Tokens in
localStorage; long-lived tokens without rotation; tokens in URLs (logged, leaked via Referer).
- Trusting
postMessage without checking event.origin; target="_blank" to untrusted URLs without noopener in old browsers.
- Rendering user-supplied URLs without scheme checks (
javascript:).
- Copy-pasting third-party scripts from CDNs without SRI; adding packages without review.
- Treating frontend checks or hidden buttons as authorisation.
Glossary
- Sink: an API that turns a string into code or markup (
innerHTML, eval).
- Nonce: a random single-use value tying allowed scripts to one response.
- SRI: Subresource Integrity, hash-pinning a fetched script or stylesheet.
- PKCE: Proof Key for Code Exchange, protecting the OAuth code flow in public clients.
- BFF: Backend for Frontend, a server-side component that holds tokens and exposes a session cookie to the SPA.
- Gadget: existing library code that turns a primitive (like prototype pollution) into a real exploit.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
"Sanitise, then assign to innerHTML." |
Under Trusted Types, a sanitised string is refused; only a trusted value from a named policy works. |
| "Send both report-to and report-uri for coverage." |
With report-to present, Chromium ignored report-uri. |
| "A nonce is a secret on the page." |
Any running script can read it as a property. |
| "Fetch Metadata is enough against CSRF." |
Older browsers don't send it; the build now checks Origin too. |
| "CORS stops cross-site requests." |
It controls who reads responses; the request still happens. |
| "DOMPurify removes everything risky." |
It keeps what's inert by its rules (a data: SVG image); context matters. |
29
Key ideas
- Service workers: register → install (precache) → wait → activate (claim, clean old caches) → fetch/push/sync events; scope by path; HTTPS only; updates wait for old clients unless
skipWaiting().
- Caching strategies: cache first (versioned assets), network first (fresh data with offline fallback), stale-while-revalidate (fast and eventually fresh), network only, cache only; navigation preload; offline fallback pages.
- Offline data: IndexedDB as the local database; background sync to retry writes; conflict handling.
- Push: Push API + Notifications via the service worker; permission UX; iOS supports web push for installed PWAs.
- Manifest and install: name, icons,
start_url, display, theme colours, shortcuts, share target; installability prompts differ by browser.
- Web Workers: dedicated and shared workers; message passing with structured clone; transferables;
SharedArrayBuffer + Atomics with cross-origin isolation; OffscreenCanvas; worker pools; Comlink.
- WebAssembly: stack-machine bytecode with linear memory; imports and exports; toolchains (Emscripten, wasm-bindgen/wasm-pack, Zig, TinyGo/Go, .NET, Kotlin/Wasm with WasmGC); WASI outside the browser; SIMD, threads, exception handling and GC proposals.
Numbers to remember
- Lab: main-thread work 11 fps vs worker 60 fps; copying 100 MB 659 ms vs transferring 1.8 ms.
- Lab: Mandelbrot JS 149 ms ≈ Wasm 148 ms; 10M boundary calls 28 ms vs 5 ms; 64-bit hash BigInt ≈ 146 ms vs Wasm 9 ms.
Pitfalls
- Caching HTML cache-first with no update path; never deleting old caches; a broken
sw.js cached forever (serve it with Cache-Control: no-cache).
- Expecting the first page load to be controlled without
clients.claim().
- Posting huge objects to workers instead of transferring buffers.
- Using Wasm for UI logic or making fine-grained calls across the boundary.
- Shipping multi-megabyte Wasm without streaming compilation, compression and caching.
Glossary
- PWA: a web app with a manifest and service worker that can install and work offline.
- App shell: the minimal HTML, CSS and JS needed to render the UI, cached for instant loads.
- Transferable: an object whose ownership moves to another thread without copying.
- Linear memory: a Wasm module's single resizable byte array.
- WASI: the WebAssembly System Interface for running Wasm outside browsers.
- Cross-origin isolation: the COOP + COEP state that unlocks
SharedArrayBuffer and precise timers.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Registering a service worker is one line." |
Under Trusted Types it needs a policy the CSP names. |
"navigator.onLine tells you if requests will work." |
It stayed true with the server down. |
| "IndexedDB is permanent." |
Without persistence it can be evicted; persist() was refused. |
| "A queued request can just be sent again." |
Only if the server makes it idempotent, and only in order. |
"fetch rejects on an error response." |
It rejects only when there's no response; a 404 resolves. |
| "Cache the whole site and it works offline." |
Pages with per-response secrets (nonces) must never be stored. |
| "WebAssembly is faster than JavaScript." |
Only for compute-bound work that doesn't cross the boundary much. |
30
Key ideas
- Package managers (npm, pnpm, Yarn, Bun) resolve semver ranges into a dependency tree; pnpm's content-addressed store and strict
node_modules prevent phantom dependencies.
- Semver:
^ minors and patches, ~ patches; lockfiles pin exact versions and integrity hashes; npm ci for reproducible installs.
- Module systems: ESM (static, tree-shakeable, async) vs CommonJS (dynamic
require); package.json exports/imports maps with conditions (import, require, browser, types); dual packages and their hazards.
- Bundlers: dependency graph, transforms (TS/JSX via esbuild, SWC, Oxc), tree shaking, code splitting, minification, content hashing, CSS handling, asset pipelines; Vite (native-ESM dev server, Rolldown builds since Vite 8), Webpack/Rspack, Turbopack (Next.js), esbuild.
- Source maps: generated per build, uploaded to error trackers; decide whether to serve them publicly.
- Code quality: ESLint (flat config) / Biome / oxlint, Prettier or Biome formatting, TypeScript type-checking in CI, pre-commit hooks.
- Monorepos: workspaces; task graphs (
dependsOn); content-hash caching (local and remote); affected-only builds; Turborepo, Nx, Bazel; versioning and publishing with Changesets.
- Native tooling trend: Go and Rust rewrites (esbuild, SWC, Rolldown, Oxc, Biome, Turbopack, TypeScript 7) for large speedups.
Numbers to remember
- Lab:
lodash default import 26.4 KB gzipped vs lodash-es named import 1.5 KB.
- Lab: a React shopping list built to 220 KB (69 KB gzipped); the source map was about 1 MB; Vite's dev server ready in 0.2 s.
- Lab: monorepo rebuild with nothing changed: 5 ms from cache vs 5 s.
Pitfalls
- Not committing lockfiles;
npm install in CI; mixing package managers.
- CommonJS-only or side-effectful dependencies defeating tree shaking; barrel files re-exporting everything.
- Secrets in client-side environment variables (
VITE_, NEXT_PUBLIC_ values are public).
- Cache keys missing inputs (environment variables, generated files) or including outputs.
- Duplicate copies of React or other singletons from mismatched versions.
- Publicly served source maps exposing proprietary source.
Glossary
- Semver range: a version constraint like
^1.2.3.
- Lockfile: the exact resolved dependency tree with integrity hashes.
- Tree shaking: dead-code elimination based on static ES module imports and exports.
- HMR: hot module replacement, updating a running page's modules without a reload.
- Exports map: the
exports field controlling which files a package exposes under which conditions.
- Remote cache: a shared store of task outputs keyed by input hashes.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Shared types keep client and server in step." |
Not with old data or old deployed clients; contracts need optional fields and expand-then-contract. |
| "Deterministic tools make reproducible builds." |
Undeclared inputs (stale files, hand-written files in the output) break it. |
| "A workspace has one version of each package." |
Three copies of TypeScript, two of them the same version. |
| "If it imports, it's a dependency." |
Hoisting makes undeclared packages importable. |
"npm install in CI is fine." |
It can change the lockfile; npm ci installs exactly it, or fails. |
| "Dependencies only run in the browser." |
Six packages ran native install scripts on every npm ci. |
| "Our code is what makes the bundle big." |
It was 9% of the React view. |
31
Key ideas
- Static hosting: object storage + CDN, or a static platform; SPA fallback for page routes only; correct content types; HTTPS everywhere with HSTS.
- Server-rendered hosting: long-running Node servers (containers, VMs), serverless functions, edge runtimes; their trade-offs in cold starts, limits, cost and distance to data.
- Caching: hashed assets
immutable for a year; HTML no-cache; Vary correctness; s-maxage and stale-while-revalidate for CDN-cached HTML; purge/invalidate HTML, never needed for hashed assets.
- Releases: immutable, complete releases; atomic pointer switch; keep old hashed assets; handle chunk-load errors with a reload prompt; preview deployments per pull request.
- Configuration: build once, promote everywhere; runtime config (
/config.json, server-injected) over build-time baking; nothing in the client is secret.
- Containers and proxies: multi-stage Docker builds (build in Node, serve with nginx or a minimal runtime); reverse proxies for TLS, compression, routing, rate limits and security headers.
- Rollout and rollback: gradual percentage rollouts, canaries watched with error and Web Vitals metrics, feature flags, instant rollback by switching releases.
Numbers to remember
- Lab: copying over the live folder broke about 26% of page loads during deploys; pointer switch with retained assets broke 0 of 2,974.
- Light in fibre: about 200 km per ms; a far origin can add 100–200 ms per round trip that a nearby CDN location avoids.
max-age=31536000 = one year.
Pitfalls
- Fallback returning HTML for missing assets (and CDNs caching it).
- Deleting old assets on deploy; uploading
index.html before its assets.
- Long
max-age on HTML; CDN caching of personalised or authenticated responses.
- Secrets in frontend config; different builds per environment.
- Service workers (chapter 29) pinning users to an old release with no update path.
- No rollback plan or untested rollback.
Glossary
- Origin: the server or bucket a CDN fetches from on a cache miss.
- Cache hit ratio: the fraction of requests a CDN serves without contacting the origin.
- Atomic deploy: switching from one complete release to another in a single step.
- Preview deployment: a per-branch or per-PR deployment with its own URL.
- Canary release: sending a small share of traffic to a new version first.
- Edge runtime: a lightweight JavaScript runtime running at CDN locations.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Keep old files and deploys are safe." |
Also in the rollback direction, or rollbacks 404. |
| "A proxy passes a stream through." |
nginx's default held it back entirely. |
| "The six-connection limit only slows things down." |
The seventh tab couldn't load at all. |
| "An ETag tells the browser whether a file changed." |
serve-static's ETag changes when the file's time does, even with the same bytes. |
| "Cache-busting query strings are as good as hashed names." |
Some caches ignore query strings, and the file itself can't be kept for old tabs. |
| "Content hashes depend only on content." |
esbuild's names changed with the build directory until the paths were made relative. |
"immutable is what makes assets long-lived." |
The year-long max-age does that; immutable only stops revalidation on reload (Firefox and Safari honour it; Chrome changed its reload behaviour instead). |
32
Key ideas
- The frontend runs on devices you don't control; without client telemetry, errors and slowness are invisible.
- Error tracking:
error and unhandledrejection handlers (plus framework error boundaries); grouping by fingerprint; breadcrumbs; release tagging; source maps uploaded per release; cross-origin scripts need crossorigin + CORS for details.
- Delivery:
sendBeacon or fetch(…, { keepalive: true }), triggered on visibilitychange to hidden (the last reliable moment, especially on mobile); batching; sampling.
- RUM: Web Vitals via
web-vitals (with attribution builds), navigation and resource timing, long animation frames; summarise with percentiles and distributions by segment.
- Tracing: W3C Trace Context (
traceparent, tracestate), OpenTelemetry web SDK, spans for page loads, route changes and fetches, propagation only to allowed origins; correlation ids in logs.
- Session context and replay: route, release, feature flags, device; session replay with input masking.
- Release health: crash-free sessions, error rate and Web Vitals per release; canary comparison; fast rollback.
- Privacy: no secrets or personal data in telemetry; masking; consent; data retention.
Numbers to remember
- Lab: average LCP 2,050 ms while 23.9% of visits exceeded 2.5 s; p75 2,397 ms; p95 5,573 ms.
traceparent = version 00 - 32-hex trace id - 16-hex parent span id - flags (01 sampled).
Pitfalls
- Only listening for
error and missing rejected promises; not reporting HTTP failures.
- "Script error." from CDN-hosted bundles without
crossorigin.
- Averages on dashboards; no segmentation; no release dimension.
- Sending telemetry on
unload (unreliable on mobile, blocks the bfcache).
- Unbounded volume (every console log, 100% sampling) and cost surprises.
- Personal data in URLs, error messages and replays.
Glossary
- RUM: real-user monitoring, performance data from actual visits.
- Breadcrumbs: the recent events (clicks, navigations, requests, logs) attached to an error report.
- Fingerprint: the key that groups identical errors together.
- Span: one timed operation in a trace, with a parent.
- Sampling: recording a fraction of sessions or traces to control cost.
- Release health: error and performance metrics compared per deployed version.
Practise: Exercises · Companion · TiffinBox stage
Misconceptions (from the companion)
| Misconception |
What's actually true |
| "Send on hide and you'll get everything." |
A page that's never hidden sends nothing. |
"sendBeacon always sends." |
It refused 63 KB with 17 KB in flight, and said so only by returning false. |
| "Group errors by their top frame." |
The top frame was the shared helper fail. |
| "INP is the slowest interaction." |
It's about the 98th percentile: web-vitals takes the (n/50)th longest. |
| "Source maps are harmless to serve." |
They publish your source, and nothing needs them but your error tool. |
| "More tags make better data." |
Each value is a new series; unbounded tags exhaust storage. |
| "Field LCP is the same as lab LCP." |
Field LCP stops at the first input, and includes real networks and devices. |