Workbench / Volume 2 Companion: The Web Frontend
V2·24
Full-Stack Frameworks
Companion to Volume 2, chapter 24: how rendering strategies, frameworks and production concerns connect; new angles (CSR as flat-pack furniture, SSR as a furnished flat, streaming as courses served as they're ready, islands as a house where only some rooms have electricity); what the chapter simplifies, measured: hydrating 500 server-rendered cards cost as much main-thread time as rendering them from nothing, plus a 211–328 ms task to parse and lay out the HTML; streaming through gzip works only because React calls flush(), and one ordinary stream in between turned two chunks into one at 804 ms; and serialised state, where JSON loses dates, sets and shared objects and keeps </script>, while devalue keeps everything and gzips 2.5 times worse; the theory behind it; how devalue serialises a graph and escapes it for a script tag; four debugging drills, including a development-mode server that put its file paths in the HTML; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 24 has three strands. Where and when HTML is made: CSR, SSR with hydration, SSG and ISR, streaming and partial prerendering, islands and Server Components, edge rendering. Frameworks: Next.js, React Router, Astro, SvelteKit and Nuxt, and how to choose. Next.js in production: the App Router, loading and error boundaries, server actions and route handlers, caching, metadata, images and fonts, and the deployment runtime.
The links worth remembering:
- Each strategy moves work in time and place. CSR does everything in the browser at view time; SSR moves HTML to the server at request time; SSG moves it to build time; streaming splits it across the response; islands remove the JavaScript that didn't need to exist. None makes work disappear (Gaps 1).
- The server's output is a contract with the client. HTML, embedded state and the client's first render must agree, or hydration throws work away (the lab's Experiment 3); embedded state must survive serialisation and must not end its script tag (Gaps 3).
- Every layer between server and user can undo the strategy. A buffering proxy, a compression layer or a CDN cache decides what the user really receives, and when (Gaps 2).
Explain it differently
1. CSR is flat-pack furniture. The box arrives fast and small, and the customer spends the evening assembling it. SSR delivers it assembled: heavier, slower to leave the warehouse, usable the moment it's through the door.
2. Hydration is moving into a furnished flat. The furniture is there (HTML), but nothing works until the electrician walks every room connecting the wiring (event handlers, state). The electrician still visits every room, even the ones with nothing to switch on (Gaps 1).
3. Streaming is a restaurant serving courses as they're ready. Starters arrive while the main course cooks. If the waiter insists on bringing the whole meal on one tray (a buffering layer), the kitchen's timing is wasted (Gaps 2).
4. Islands are a house where only some rooms have electricity. The hall and the bedrooms are fine with daylight (static HTML); the kitchen and the study need power (interactive components). Wiring only those rooms is cheaper and faster than wiring the whole house.
5. ISR is a newspaper's evening edition. The morning paper is printed once and sold all day; when news breaks, a new edition is printed and the old one is sold until it's ready. Readers sometimes get the earlier edition, and that's the deal.
6. Serialising state is packing for a move. JSON is a box that only takes clothes: dates become paper notes, sets fall apart, two references to the same lamp become two lamps. A better removals firm (devalue) labels everything and keeps pairs together, at the cost of more paperwork (Gaps 3).
7. A server action is a letterbox with a hidden address. Anyone who finds the slot can post to it, so it checks what's posted and who posted it every time (Chapter Exercises P5).
8. Edge rendering is a pop-up kitchen near the customers. Fast to reach, small, and far from the main storeroom: fine for reheating, slow for anything that needs the pantry (the database) on every order.
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from React 19.1.1, devalue 5.1.1, Node 22 and Chromium with the CPU throttled 4× (exp/24), unless stated.
1. Hydration costs about as much as rendering, after the HTML has cost its own. The chapter says the hydration cost "remains". How much: 500 order cards (a heading, two lines, a button each), three ways, three runs each: the HTML alone with no script, an empty page that renders them with createRoot, and server HTML hydrated with hydrateRoot:
html: first contentful paint 360 ms | script start to commit -1 ms | long tasks [254]
csr : first contentful paint 684 ms | script start to commit 460 ms | long tasks [147, 105]
ssr : first contentful paint 376 ms | script start to commit 328 ms | long tasks [291, 109, 123]
html: first contentful paint 372 ms | script start to commit -1 ms | long tasks [289]
csr : first contentful paint 500 ms | script start to commit 322 ms | long tasks [105, 97]
ssr : first contentful paint 416 ms | script start to commit 440 ms | long tasks [328, 133, 143]
html: first contentful paint 344 ms | script start to commit -1 ms | long tasks [227]
csr : first contentful paint 456 ms | script start to commit 282 ms | long tasks [110, 66]
ssr : first contentful paint 312 ms | script start to commit 319 ms | long tasks [211, 105, 114]
Server HTML put content on screen 100–300 ms sooner, as promised. But hydrating took as long as rendering from nothing (319–440 ms against 282–460 ms from the script's start to React's first commit): hydration still runs every component and walks every node, it just attaches to existing DOM instead of creating it. And the HTML itself costs: parsing and laying out 500 cards was a 211–328 ms task before any script ran (the html rows show it alone). Add them up and the SSR page did 430–604 ms of long tasks where CSR did 176–252. Server rendering trades main-thread time for earlier content. For a large interactive list on a slow device, that can be the wrong trade; islands, partial hydration and rendering only the first screen on the server (as the build has done since stage 21) are ways to buy the early content without paying for all of it.
2. Streaming through compression works because React calls flush(), and breaks when something in between doesn't. The lab's slow-reviews page, served four ways and read by a client that decompresses as it receives:
plain : +26 ms 131 chars (has the h1) | +820 ms 615 chars
gzip : +7 ms 131 chars (has the h1) | +806 ms 615 chars
gzip-behind: +804 ms 746 chars (has the h1)
gzip-flush : +4 ms 131 chars (has the h1) | +804 ms 601 chars | +804 ms 14 chars
Plain gzip streamed correctly, which surprised me: compressors buffer to compress well. The reason is in react-dom-server's Node build:
"function" === typeof destination.flush && destination.flush();
React calls flush() on whatever it writes to, if it has one, and Node's gzip stream does. gzip-behind put an ordinary PassThrough stream between React and gzip, the shape any logging, metrics or transform layer has: React flushed the PassThrough (which has no flush), gzip never heard about it, and the user got everything at once at 804 ms. Streaming is a property of every layer on the path; test it end to end with the real middleware, proxy and CDN, by timing chunks at the client, not by reading the server's code.
3. Serialised state: JSON loses types and keeps </script>; better serialisers cost bytes. SSR frameworks embed the server's data so the client can hydrate without fetching it again. An order with a Date, a Set, an undefined field, a dish referenced twice, a note containing </script>, and a reference to itself:
JSON.stringify: Converting circular structure to JSON
JSON round trip: {"at":"string","tags":{},"hasDiscount":false,"sameDish":false} | contains </script>: true
devalue: [{"id":1,"at":2,"tags":3,"discount":-1,"note":5,"lines":6,"self":0},"o1",["Date","2026-11-15T10:00:00.000Z"],["Set",4],"spicy","</script><script>alert(1)</script>",[7,7],{"id":8,"name":9},"d1","Masala dosa"]
devalue round trip: {"at":true,"tags":true,"hasDiscount":true,"sameDish":true,"cycle":true}
500 orders: JSON 110969 bytes (4908 gzipped) | devalue 109960 bytes (12295 gzipped)
JSON refused the cycle; without it, the date came back as a string, the set as {}, the undefined field vanished, the shared dish became two objects, and </script> was still there to end the script element (chapter 22's companion). devalue (SvelteKit's serialiser) kept all of it and escaped <. But on the build's real 500-order kitchen state, devalue's output, though slightly shorter, gzipped 2.5 times worse: replacing repeated values with indices removes exactly the repetition gzip exploits. And either way the page now carries its data twice, once as HTML and once as state: the build's kitchen page went from 12,008 bytes (1,277 gzipped) to 123,041 bytes (5,946 gzipped) when stage 24 embedded its state. Choose the format by what the data contains (plain JSON with ISO strings is enough for the build's contract-checked types), always escape for the script context, and measure compressed size.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "SSR makes pages faster." | It makes content visible sooner; total main-thread work went up. | Gaps 1 |
| "Hydration is cheaper than rendering." | It took as long as rendering from nothing here. | Gaps 1 |
| "Compression breaks streaming." | Only where a layer doesn't pass flush() through. |
Gaps 2 |
"JSON.stringify is fine for embedding state." |
It loses types and doesn't escape </script>. |
Gaps 3 |
| "A slow data source just makes the page slow." | Without a deadline the response never ended. | Drill D2 |
| "Development and production SSR send the same HTML." | Development put the server's error message and file paths in the page. | Drill D3 |
Theoretical gaps: the ideas behind the chapter
1. Rendering is a function; strategies choose when to evaluate it. HTML = render(data, request). CSR evaluates it lazily on the client, SSR eagerly per request, SSG once at build time and caches the result, ISR caches with a time-to-live. That's memoisation with different keys and lifetimes, and the cache-invalidation problem comes with it.
2. Hydration is replay; resumability serialises the program's state. Hydration re-executes components to rebuild the closures and state the server had (the cost Gaps 1 measures). Resumable frameworks (Qwik) serialise enough of that state and handler locations into the HTML to continue without re-executing. Server Components avoid both for components that need no client state. It's the same choice as checkpoint/restore versus re-running a computation.
3. Streaming is a pipeline, and pipelines need back-pressure and flushing. Every stage between producer and consumer either passes data through promptly or buffers it. Buffering improves throughput (compression ratio, fewer packets) and hurts latency; flush is the explicit signal to trade the other way. It's the same trade as Nagle's algorithm in TCP (Volume 1's networking chapters).
4. Serialisation is graph encoding. JSON encodes trees of six types; real program state is a graph with richer types. Encoding a graph needs identity (indices or references) and type tags, which is what devalue, structured clone and Java serialisation add. Each format is a contract, and each must be escaped for the context it's embedded in (HTML text, attribute, script).
5. Consistency between server and client renders. Hydration requires the client's first render to equal the server's output: a distributed system with two replicas computing the same function. Anything nondeterministic (time, random numbers, locale, user agent) breaks it, as clocks and randomness break replicated state machines.
6. Caches turn correctness into a time question. ISR, CDN caching and revalidation make "is this page right?" depend on when it was generated and for whom. A cache key that leaves out something the page depends on (a cookie, a header) serves one user's page to another: the most serious class of caching bug.
Applying it
Code walkthrough
Gaps 3 used devalue, the serialiser SvelteKit uses to embed server data in pages. Excerpts from devalue 5.1.1, src/stringify.js and src/utils.js, installed from npm.
Flattening a graph into an array
function flatten(thing) {
if (typeof thing === 'function') {
throw new DevalueError(`Cannot stringify a function`, keys);
}
if (indexes.has(thing)) return indexes.get(thing);
if (thing === undefined) return UNDEFINED;
if (Number.isNaN(thing)) return NAN;
if (thing === Infinity) return POSITIVE_INFINITY;
if (thing === -Infinity) return NEGATIVE_INFINITY;
if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO;
const index = p++;
indexes.set(thing, index);
// …
case 'Date':
const valid = !isNaN(thing.getDate());
str = `["Date","${valid ? thing.toISOString() : ''}"]`;
break;
Every value gets a slot in one flat array, and every reference becomes the slot's number. indexes is a Map keyed by the value itself, so an object seen before (a shared dish, or the object containing itself) returns its existing index: that's how cycles and shared references survive. The same Map also catches repeated primitives: the second "Placed" is index 4 again, not a new string. Values JSON can't express (undefined, NaN, ±Infinity, -0) become negative constants, and types become tagged arrays (["Date", "…"], ["Set", …]). Functions are refused, with the path to them in the error (keys).
Escaping for a script element
function get_escaped_char(char) {
switch (char) {
case '"':
return '\\"';
case '<':
return '\\u003C';
case '\\':
return '\\\\';
// …
case '
':
return '\\u2028';
case '
':
return '\\u2029';
default:
return char < ' '
? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
: '';
}
}
Strings are escaped as JSON would, plus < as <, which makes </script> and <!-- impossible inside the output, and the two line separators that older JavaScript parsers treated as line ends. The output is meant to sit inside a <script> element and be parsed by devalue's parse (or evaluated, by its uneval sibling). The build's Html.scriptJson (stage 24) does the same for plain JSON, escaping > and & too.
Read it yourself
- Before running it: what does devalue produce for
[s, s, s]wheres = "Placed", and for[{a: 1}, {a: 1}](two separate but equal objects)? Then run it. - Why did devalue's output for 500 orders gzip so much worse than JSON's? Take the first 300 characters of each and look at what repeats.
Debugging drills
D1. The kitchen display flickers empty when it loads
The React view of the kitchen display shows the server's first 40 cards, then nothing for a moment, then its own cards. On the throttled tablet profile the empty moment is visible. main.tsx replaces the server's list with a mount point and calls createRoot(mount).render(…); the store waits for the stream's snapshot.
D2. Some product pages never finish loading
A streamed product page sometimes never finishes: the name and price show, "Loading reviews…" stays forever, and the server's connection count climbs. The reviews service occasionally hangs without answering.
D3. The page source shows your server's file paths
A security review of the staging site finds this in a page's HTML, inside a script: Switched to client rendering because the server rendering aborted due to:\n\nError: reviews took longer than 1 s\n at Timeout._onTimeout (file:///tmp/npm24/abort.mjs…. Production is "the same build".
D4. "Connecting…" for 15 seconds on a perfectly good connection
After stage 24, the framework views start from the page's embedded state and open the stream with ?after=<id>. On a quiet kitchen (no new orders), the status line says "Connecting…" for 15 seconds after every load, then "Live". With orders arriving, it's fine.
Career-oriented
Interview prep
Mid level
Q1. A colleague says "we should server-render the order dashboard to make it faster". What do you ask before agreeing?
How to get there. Separate "faster to see" from "faster to use", and ask who uses the page, on what, how often.
Q2. How do you embed server data in an HTML page safely?
How to get there. Think about the HTML parser's view of a script element, and about types.
Senior level
Q3. Your streamed pages behave correctly locally, but in production users see the whole page arrive at once. How do you find the cause?
How to get there. List every layer between the render and the user, and test each.
Q4. Design SSR error handling for a page with three data sources of different importance.
How to get there. Decide per source what the page should do when it's slow and when it fails.
Staff level
Q5. Your organisation runs a Java backend that renders HTML (like the build's) and is adding React applications. Some teams want a Node rendering tier for SSR. Decide.
How to get there. Weigh what a second runtime costs against what it buys, and consider the alternatives the build used.
Q6. Set the rules for what may be cached, and where, across server-rendered pages.
How to get there. Think about what each page depends on, and which caches sit between server and user.