When pages styled with a runtime CSS-in-JS library are server-rendered with streaming, how must the library collect its styles, and why does one stylesheet in the head no longer work?
answer
- class names without their rules
- collect during the server render
- the head leaves before slow parts render
- flush with each chunk, ahead of the markup
- clear what was sent
basics
~20 sOn the server the library must collect the rules each render produces and write them into the HTML, or the first paint is unstyled. Streaming sends the head early, so rules must be flushed with each chunk, ahead of the markup using them.
solid answer
~50 sA runtime library normally inserts rules in the browser, so server HTML would carry class names with no rules behind them until the client JavaScript loads and injects them. Server rendering therefore needs a **collector**, created per request, that records every rule generated during the render and writes it into the HTML as `<style>` elements; the client library then picks up those rules rather than regenerating them. Without streaming, the whole page renders first and the collected CSS goes into the head. With **streaming**, the head is sent before slower parts of the tree have rendered, so their rules do not exist yet. The collector must flush whatever it gathered since the last flush **with each chunk, ahead of the markup that uses it**, and clear what it sent so no rule is sent twice. A simpler variant writes a `<style>` element directly before each element.
go deeper
Remember that a runtime library's rules do not exist in server HTML unless something collects them during the render and writes them into the page.
Explain the per-request collector: record rules during rendering, emit them as style elements, and let the client library continue from the rules already in the page.
Explain why streaming forces per-chunk flushing ahead of the markup, how clearing prevents duplicates, and what inline-before-element emission does to child-counting selectors.
Weigh the operational cost of collectors, stream hooks and selector caveats across the apps you own against moving shared components to build-time extraction.
## The problem server rendering creates A **runtime CSS-in-JS library** generates its rules while components render and, in the browser, inserts them into the document. On the server there is no document to insert into. If nothing is done, the server-rendered HTML for a concert-ticketing site's event page arrives with every element carrying a generated class name and **no rules behind any of them**: - the browser paints the page unstyled; - the styles appear only once the client bundle has downloaded, run and rendered; - the user sees a flash of unstyled content, and layout shifts as the rules arrive. Server rendering exists to make the first paint useful, so the styles must travel in the HTML. ## Collecting styles during a server render The standard answer is a **collector**: 1. Create a fresh collector for each request, so one visitor's rules never leak into another response. 2. Render the tree with the collector in scope; every rule the library generates is recorded in memory rather than inserted into a DOM. 3. Serialise the collected rules into one or more `<style>` elements in the HTML. 4. On the client, the library recognises the rules already present and continues from there rather than inserting them again. After hydration the library behaves as it does in a purely client-rendered app: components rendered later, such as a seat-selection dialog opened by a click, generate their rules and insert them in the browser. styled-components, for example, records rules into an in-memory list on the server and emits them as a `<style>` element marked with its own data attribute; Emotion's documentation states that hydration of the server-emitted ids happens automatically when its cache is created on the client. ## Why streaming breaks "everything in the head" Without streaming, the server renders the whole page, then sends it, so the collected CSS can go into `<head>` in one piece. **Streaming** changes the order. The server sends the first part of the document, including the head, as soon as it is ready, and slower parts of the tree, such as a seat-availability panel waiting for an API, render later and arrive in later chunks. By then: - the head has already gone out and cannot be appended to; - the rules for the slow parts did not exist when the head was sent. So a streaming-aware collector **flushes with each chunk**. styled-components 6.5.3's server style sheet shows the mechanism plainly: its stream transform takes the CSS collected so far, clears the collected rules, and pushes a `<style>` element ahead of the chunk's HTML (or right after a leading closing tag), so each rule is sent once and before the markup that uses it. ## Two strategies compared | Strategy | How rules reach the HTML | Streaming | Catch | |---|---|---|---| | Collect and flush per chunk | A `<style>` element per flushed chunk | Works | Needs a hook into the response stream | | Inline before each element | A `<style>` element immediately before each styled element | Works | Extra elements among siblings | | Collect everything, then inject into the head | One `<style>` element in the head after rendering completes | Does not work | Requires the full page before sending | Emotion's server-rendering guide describes the second and third approaches: its default inserts a `<style>` tag above each element, works with streaming and needs no configuration, but interferes with `:nth-child` and similar selectors because the style elements become siblings of the styled elements; its advanced approach extracts critical CSS from a fully rendered string and does not work with the streaming APIs. ## What to check in production - **Ordering**: a rule must appear in the byte stream before the markup that needs it, or that markup paints unstyled for a moment. - **Duplicates**: flushing must clear what was sent, otherwise every chunk repeats the whole sheet. - **Per-request state**: a collector shared across requests mixes visitors' styles and grows without bound. - **Framework glue**: frameworks that stream usually expose a way to insert HTML before each chunk; the library's collector plugs into it, and how that integration is configured is framework-specific. - **Extraction sidesteps all of it**: a zero-runtime library's static stylesheet is linked once in the head, so there is nothing to collect or flush.
- Why must the collector be created per request rather than once per server?It accumulates every rule a render generates. Shared across requests, it would send one visitor's rules in another's response, flush rules that the current page never uses, and grow for the life of the process. A per-request collector starts empty, matches exactly what this render produced, and is discarded afterwards.
- What does the browser show if a chunk's rules arrive after its markup?The markup is parsed and can paint with its class names unmatched, so that part of the page appears unstyled until the later style element is parsed, then jumps into place. That is why a flushing collector places each batch of rules ahead of the chunk's HTML.
- Server-rendered HTML is styled automatically because classes are in the markup
- One style element in the head is enough for a streamed page
- A single collector can be shared safely across all server requests
- Writing a style element before each element has no side effects on selectors
- Each flushed chunk should resend the full collected stylesheet