Skip to content

Commit 209317c

Browse files
authored
fix(rsc): send repeated server-component styles once, and explain edge-runtime failures (#5825)
* docs: payload dedup, precedence reasons, edge runtime, and lightweight-package bar Corrects the Float claims in rsc-style-injection.md (plain styles keep their attributes everywhere; precedence fails by bucket order, permanence, attribute loss and position), specifies one shared style element per key for the server-component payload, records why there is no exports map and why edge server rendering is unsupported, and fixes the FAQ's advice for long server-rendered lists. * perf(rsc): share one style element across identical global style instances * perf(rsc): share one style element across styled component instances with identical classes * feat: clear errors when the browser build loads in an edge-runtime server render * docs: correct the createGlobalStyle server-detection comment * docs: add changeset for the edge runtime error * perf(rsc): wrap the shared global style element in an array so the payload references it whole * docs: record the class-string key and array-wrapped globals; drop guard byte counts * docs: key styled-component elements on component ID plus classes; correct the styleSheet.server rationale * fix(rsc): key the shared style element on component ID plus classes An extension with no CSS of its own returns exactly its base's class string, but its CSS wraps the base in :where() and its React key differs, so whichever rendered first handed the other the wrong element. * refactor(rsc): build the style CSS in a module-level function The hook body now asks buildRSCStyleCSS for the combined CSS and creates the shared element only when it is non-empty. The comments describe the element sharing instead of reading as no dedup. * fix(rsc): point edge-runtime errors at the server build and correct the guard comments Errors 19 and 20 now also cover a server bundle that resolves the browser build. The edge tests assert against the generated error map. The redundant-emit warning names its count without 'Over', since it fires at exactly the threshold. * test(rsc): read shared style elements without spying on createElement The payload-dedup tests call the component's render function directly, fold the namespace and stylisPlugins cases into one table, fold the fixed-key checks into the distinct-element tests, and drop the duplicated tag count and the any casts. The empty-leaf interpolation case keeps its single-line template so the leaf earns no class of its own. * style: wrap the edge guard comment * docs: drop the agent rule against starting dev servers * docs: note that the sandbox loads the built dist
1 parent 7afbd11 commit 209317c

16 files changed

Lines changed: 621 additions & 112 deletions

‎.changeset/edge-runtime-error.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"styled-components": patch
3+
---
4+
5+
Rendering styled-components on the server with the edge runtime (for example `export const runtime = 'edge'` in a Next.js route) now fails with a clear message that names the fix: use the Node.js runtime for routes that render styled-components. Previously the same setup ended in an obscure crash, either at `next build` or on the first request.

‎.changeset/rsc-suspense-style-removal.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44

55
Fixed styles disappearing from a server-rendered component when it is revealed from behind a React `<Suspense>` boundary, such as a streaming Next.js route (including `cacheComponents`). A component shown first in a Suspense fallback and then in the resolved content kept its class name but lost its CSS, because the rule had been emitted only inside the fallback that React discards on reveal.
66

7-
Each server-rendered instance now carries its own inline `<style>`, so its styles always travel with it and survive the boundary. Nearby duplicates still compress away almost for free under gzip, but gzip can only look back about 32 KB, so once repeats are farther apart on the page each one costs roughly its own compressed size; brotli's much larger window keeps it cheap regardless of distance. Only a very large repeated list (thousands of instances of one component on a single page) is worth collapsing into a shared class, and a development-only warning points that out if it happens.
7+
Each server-rendered instance now carries its own inline `<style>`, so its styles always travel with it and survive the boundary. The data React sends for server components includes each distinct style once on React 19, however many instances repeat it. In the HTML, nearby duplicates compress away almost for free under gzip, but gzip can only look back about 32 KB, so once repeats are farther apart on the page each one costs roughly its own compressed size; brotli's much larger window keeps it cheap regardless of distance. Only a very large repeated list (thousands of instances of one component on a single page) is worth restyling from a single parent element, and a development-only warning points that out if it happens.

‎AGENTS.md‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,18 @@ mapped below.
44
## Basics
55

66
- Use pnpm package manager and associated commands
7-
- Never run the dev server yourself, ask the user to start it if needed
87
- Use conventional commits: `(feat|fix|chore|refactor|test|docs|style|perf|build|ci): [description]`
98

109
## Critical Constraints
1110

11+
- We strive for perfection in the lightest and quickest package. A change proves its cost against the
12+
prior code before landing: shipped bundle bytes, emitted output bytes (CSS, HTML, server-component
13+
payload), and render time, measured before and after; a regression in any needs a stated reason
1214
- NEVER use `precedence` or `href` on `<style>` elements. React 19 Float merges same-precedence tags,
13-
strips custom `data-*` attributes, and hoists to `<head>` where source ordering is unpredictable.
14-
See [docs/rsc-style-injection.md](docs/rsc-style-injection.md).
15+
strips custom `data-*` attributes, and hoists to `<head>`, where the bucket lands ahead of the client
16+
registry and never unmounts. See [docs/rsc-style-injection.md](docs/rsc-style-injection.md).
17+
- Server rendering requires the Node.js runtime; edge bundles load the browser build. NEVER add an
18+
`exports` map to work around it. See [docs/build-architecture.md](docs/build-architecture.md).
1519
- The native entry must NEVER transitively import DOM code via a value import. Use `import type` and
1620
branded `Symbol.for()` checks instead of `instanceof`. Verify:
1721
`grep -c 'document\.' native/dist/styled-components.native.cjs.js` must be 0.
@@ -65,7 +69,8 @@ mapped below.
6569

6670
- `pnpm build` -- Build main package
6771
- `pnpm test` -- Run all tests
68-
- `pnpm --filter sandbox dev` -- Start Next.js dev server
72+
- `pnpm --filter sandbox dev` -- Start Next.js dev server. The sandbox loads the built `dist`, not
73+
`src`; run `pnpm build` after source changes and before validating in the sandbox
6974
- `pnpm --filter styled-components test:web` -- Test web build
7075
- `pnpm --filter styled-components test:native` -- Test React Native
7176
- `pnpm --filter styled-components test:types` -- Type contract suites (compile-only, no runner)

‎docs/build-architecture.md‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ automatically. In browser, standalone and native builds rollup replaces the expr
2020
for dead-code elimination. Because it is module-level rather than per-render, gating a hook behind it
2121
does not violate the rules of hooks.
2222

23-
`styleSheet.server` is a runtime flag set by `ServerStyleSheet`. It exists because Turbopack resolves
24-
the `browser` entry when server-rendering client components, which makes `__SERVER__` false on the
25-
server; this flag is the fallback that still reports the truth there.
23+
`styleSheet.server` is a runtime flag set by `ServerStyleSheet`. It lets a sheet forced into server
24+
mode collect styles synchronously in a build where `__SERVER__` is false (#3551). It does not make
25+
the browser build work on a server: that build's tags are always DOM tags, so a server render there
26+
fails at the first `<style>` creation (see "Edge runtime").
2627

2728
Combine all three (`__SERVER__ || IS_RSC || ssc.styleSheet.server`) with one deliberate exception:
2829
`createGlobalStyle`'s server-cache cleanup drops the `IS_RSC` term, because the `IS_RSC` branch above
@@ -47,8 +48,30 @@ Verify with `grep -c 'document\.' native/dist/styled-components.native.cjs.js`,
4748

4849
## Module resolution
4950

50-
The `browser` field in `package.json` maps server bundles to their browser-specific alternatives. It
51-
is preferred over `exports`, which caused TS2742 in composite TypeScript projects.
51+
The `browser` field in `package.json` maps server bundles to their browser-specific alternatives.
52+
There is no `exports` map. The 6.3.7 attempt was reverted for TS2742 in composite TypeScript projects
53+
(#5648) and two installed copies of the package (#5659), and no map can keep every current consumer
54+
on the file it resolves today: Jest under jsdom and Metro (Expo web) send identical conditions
55+
(`default`, `require` or `import`, `browser`) yet land on different files (`server.cjs` versus
56+
`browser.esm`). The best candidate map passed every bundler, Next.js byte-identity, composite
57+
TypeScript, and both revert cases, but moved every Jest-jsdom suite onto the browser build. Jest 29's
58+
resolver (`resolve.exports` 2.0.3) also throws when a matched condition has no inner match, where
59+
Metro falls back to the next key, so a nested map cannot paper over the difference.
60+
61+
### Edge runtime
62+
63+
Server rendering on an edge runtime is unsupported. Next.js applies the `browser` file map to edge
64+
bundles, so the server loads the browser build:
65+
66+
- A server component fails `next build`: the browser build calls `React.createContext` at module
67+
load, and the `react-server` build of React has none. Error 19 reports this, thrown from a guard in
68+
`src/constants.ts` (`!IS_RSC && !React.createContext`).
69+
- A client component crashes at request time on the first DOM access. Error 20 reports this, thrown
70+
from a `typeof document` guard at the top of `makeStyleTag` in `src/sheet/dom.ts`.
71+
72+
Both messages tell the reader to use the Node.js runtime; the message text lives in the development
73+
error map, so a consumer's production bundle carries only the two guards. Neither guard spells
74+
`typeof React.createContext === 'undefined'`, which rollup replaces with `false` in browser builds.
5275

5376
## Type package dependencies
5477

‎docs/rsc-style-injection.md‎

Lines changed: 57 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,22 @@ How styles reach the page from React Server Components.
55
## Plain inline style tags
66

77
RSC components emit plain inline `<style data-styled>` tags, with no `precedence` and no `href`.
8-
Server component output is not hydrated by React, so an inline tag causes no hydration mismatch. The
9-
`data-styled` attribute survives because React Float only strips attributes during client hydration,
10-
which never runs over RSC output.
8+
React Float only takes over a `<style>` carrying both `precedence` and `href`; a plain one renders as
9+
an ordinary host element on the server and the client, attributes intact. The client renders the same
10+
element from the server-component payload, so it hydrates against the server HTML without a mismatch.
1111

1212
Inline body styles land after the registry's `<head>` styles in source order, so a cross-boundary
13-
extension (an RSC component extending a client component) wins the cascade. This source-order
14-
placement is load-bearing and is why styles are not hoisted to `<head>` via `precedence`: the server
15-
never sees a client component's base class, so it cannot make the extension win by specificity, and
16-
`precedence` buckets order the RSC render ahead of the client registry, which would flip the cascade
17-
(#5672). The child-index selector plugin below likewise depends on the tag staying an inline sibling.
13+
extension (an RSC component extending a client component) wins the cascade. This placement is
14+
load-bearing, and `precedence` breaks it in four ways:
15+
16+
- Bucket order: Float inserts a new precedence bucket after the last `[data-precedence]` node, or at
17+
`head.firstChild` when none exists, so the RSC styles land ahead of the client registry and the
18+
extension loses to its client base (#5672).
19+
- Permanence: a precedence style is a resource that never unmounts, so styles outlive the components
20+
that rendered them (#5641, #5649, #5670).
21+
- Attribute loss: when Fizz merges a style into a bucket it keeps only `children`, so `data-styled`
22+
is dropped on the server too.
23+
- Position: the child-index selector plugin below depends on the tag staying an inline sibling.
1824

1925
No cleanup of RSC style tags is needed: they are the sole source of CSS for server-only components.
2026

@@ -34,15 +40,16 @@ on `ComponentStyle` and `Keyframes` through a `WeakMap`, which is dead-code elim
3440
build. Every name reaching emission was compiled by `generateAndInjectStyles` before it registered its
3541
class, so the per-name lookup always hits; there is no tag-group fallback.
3642

37-
There is deliberately no cross-instance or cross-request deduplication. A dedup ledger keyed on
43+
There is deliberately no cross-instance or cross-request deduplication of tags in the DOM; only the
44+
element object is shared, in the payload (see "Payload dedup"). A dedup ledger keyed on
3845
`React.cache` cannot be made safe: `React.cache` is request-wide with no per-Suspense-boundary scope,
3946
so a rule emitted only inside a Suspense fallback would be recorded once, skipped for the resolved
4047
child, then removed with the fallback when React reveals the boundary, leaving the resolved element
4148
with a class but no rule (#5808). Hoisting via `precedence` would dedup and survive the reveal, but it
42-
breaks #5672 and the child-index plugin (see above), and no per-boundary cache scope exists to make
43-
either approach safe.
49+
brings back every failure listed under "Plain inline style tags", and no per-boundary cache scope
50+
exists to make a ledger safe.
4451

45-
Byte-identical duplicates are the only output dedup ever collapsed, and their cost depends on distance
52+
In the HTML, the cost of a byte-identical duplicate depends on its distance from the previous copy
4653
in the compressed stream. Within gzip's 32 KB back-reference window, a repeat costs about a byte each
4754
(measured: 1000 identical small tags compress to ~0.5% of their raw size). Farther apart than that
4855
window, gzip can no longer reference the earlier copy, so each repeat costs roughly the gzipped size of
@@ -75,6 +82,44 @@ A development-only warning fires once a single component emits `RSC_REDUNDANT_EM
7582
instead. The counter is `React.cache`-scoped and gated on `NODE_ENV`, so production drops both the
7683
warning and its bookkeeping.
7784

85+
## Payload dedup
86+
87+
Per-instance emission repeats tags in the DOM, not in the server-component payload. Every emission
88+
site reuses one `<style>` element object per key from a request-scoped `React.cache` Map:
89+
90+
- Styled components key on the component ID plus the generated class string. The class hash covers
91+
each level's CSS text and the stylis configuration (namespace, plugin names), and the component ID
92+
fixes which level is the leaf: an extension that adds no CSS of its own returns exactly its base's
93+
class string, yet its CSS differs because every non-leaf level is wrapped in `:where()`. A hit
94+
skips rebuilding the CSS. Different CSS, different components, and subtrees under different
95+
`StyleSheetManager` namespaces or plugins never share.
96+
- `createGlobalStyle` keys on its ID plus the exact CSS text, and returns the element wrapped in an
97+
array: Flight references a repeated element whole only inside an array, while a bare returned
98+
element repeats its type and key.
99+
100+
The React key stays fixed per component (`'sc-' + componentId`, or the global's ID).
101+
102+
Sharing is safe where a ledger is not because it changes only how the payload encodes the element;
103+
every instance still renders its own tag, so a Suspense reveal that removes the fallback's copy
104+
leaves the resolved instance's copy in place. HTML and final DOM are byte-identical with and without
105+
sharing.
106+
107+
The Flight serializer (React's server-component payload writer) dedups repeated objects, and the
108+
saving depends on the build:
109+
110+
- React 19.x: every repeat after the first becomes a path reference such as `"$0:props:children:0"`,
111+
about 15 characters per nesting level.
112+
- Next.js 14.2 (vendored React 18.3 canary): the second copy is outlined into its own row and later
113+
repeats reference it, so two copies remain.
114+
- Next.js 13.5 (older vendored canary): no object dedup, so the payload is unchanged.
115+
116+
There is no size threshold below which sharing is skipped. Measured on a production Next.js 16 app
117+
(React 19.2), references ran 22 to 104 characters, always shorter than the smallest style element
118+
(129 bytes), and sharing everything was smallest or within 3 bytes in 15 of 16 compressed
119+
measurements.
120+
121+
The Map lives behind `IS_RSC`, so browser builds drop it.
122+
78123
## Per-render reset
79124

80125
`mainSheet` is reset once per server render via `React.cache`, clearing `names`, `keyframeIds` and the

‎packages/styled-components/docs/faq.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,29 @@ The registry collects styles from client components during SSR so pages are full
7474

7575
- React 16.8+ for client components
7676
- React 19+ for RSC
77+
- The Node.js runtime for any route that renders styled-components on the server. The edge runtime (`export const runtime = 'edge'`) is not supported; remove that line, or set it to `'nodejs'`
78+
79+
**Why is there a `<style>` tag before every server-rendered element?**
80+
81+
Each server component instance carries its own copy of its styles, so the styles survive React swapping a loading fallback for the finished content. The repeated tags cost little: the browser handles them quickly, compression shrinks identical copies to almost nothing, and the data React sends for server components includes each distinct style once. For a very long list, style the items from one styled parent so the whole list emits a single tag:
82+
83+
```tsx
84+
const Slides = styled.ul`
85+
& > li {
86+
scroll-snap-align: center;
87+
}
88+
`;
89+
90+
export default function Carousel({ slides }) {
91+
return (
92+
<Slides>
93+
{slides.map(slide => (
94+
<li key={slide.id}>{slide.title}</li>
95+
))}
96+
</Slides>
97+
);
98+
}
99+
```
77100

78101
**For traditional SSR (Next.js Pages Router, custom SSR):**
79102

‎packages/styled-components/src/constants.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ declare let SC_DISABLE_SPEEDY: boolean | null | undefined;
22
declare let __VERSION__: string;
33

44
import React from 'react';
5+
import styledError from './utils/error';
56

67
export const SC_ATTR: string =
78
(typeof process !== 'undefined' &&
@@ -25,6 +26,10 @@ export const IS_BROWSER = typeof window !== 'undefined' && typeof document !== '
2526
*/
2627
export const IS_RSC: boolean = typeof React.createContext === 'undefined';
2728

29+
// Fires only where the browser build is loaded next to React's server build
30+
// (docs/build-architecture.md, "Edge runtime").
31+
if (!IS_RSC && !React.createContext) throw styledError(19);
32+
2833
function readSpeedyFlag(name: string): boolean | undefined {
2934
if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {
3035
const val = process.env[name];

‎packages/styled-components/src/constructors/createGlobalStyle.ts‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ const getGlobalEmitCounts =
2828
? createRSCCache(() => new Map<string, number>())
2929
: null;
3030

31+
/** Request-scoped shared `<style>` elements (docs/rsc-style-injection.md, "Payload dedup"). */
32+
const getGlobalStyleElements = IS_RSC
33+
? createRSCCache(() => new Map<string, React.ReactElement>())
34+
: null;
35+
3136
/**
3237
* Create a component that injects global CSS when mounted. Supports theming and dynamic props.
3338
*
@@ -96,8 +101,8 @@ export default function createGlobalStyle<Props extends object>(
96101
// accumulate unboundedly in jsdom test environments (O(n²) regression).
97102
// On a real server without ServerStyleSheet, VirtualTag is used and styles are
98103
// discarded anyway, so skipping this path has no functional impact.
99-
// Turbopack resolves the browser entry for SSR, so __SERVER__ is false there;
100-
// styleSheet.server handles that case at runtime.
104+
// styleSheet.server collects styles synchronously from a sheet forced into
105+
// server mode where __SERVER__ is false (#3551, docs/build-architecture.md).
101106
if (IS_RSC || ssc.styleSheet.server) {
102107
renderStyles(instance, props, ssc.styleSheet, theme, ssc.stylis);
103108
}
@@ -172,17 +177,28 @@ export default function createGlobalStyle<Props extends object>(
172177
counts.set(styledComponentId, count);
173178
if (count === RSC_REDUNDANT_EMIT_WARN_THRESHOLD) {
174179
console.warn(
175-
`Over ${count} instances of the global style ${styledComponentId} were rendered on one server-rendered page, so its styles repeat that many times in the HTML.\n` +
180+
`${count} instances of the global style ${styledComponentId} were rendered on one server-rendered page, so its styles repeat that many times in the HTML.\n` +
176181
'A global style is normally mounted once, at the root of the app. Move it higher in the tree so it renders only once per page.'
177182
);
178183
}
179184
}
180185

181-
return React.createElement('style', {
182-
key: styledComponentId + '-' + instance,
183-
'data-styled-global': styledComponentId,
184-
children: stripSplitter(css),
185-
});
186+
// createRSCCache returns null without React.cache (React 18); emit unshared then.
187+
const styleElements = getGlobalStyleElements && getGlobalStyleElements();
188+
const styleKey = styledComponentId + '\n' + css;
189+
let styleElement = styleElements && styleElements.get(styleKey);
190+
if (!styleElement) {
191+
styleElement = React.createElement('style', {
192+
key: styledComponentId,
193+
'data-styled-global': styledComponentId,
194+
children: stripSplitter(css),
195+
});
196+
if (styleElements) styleElements.set(styleKey, styleElement);
197+
}
198+
199+
// Array-wrapped: the payload writer references a repeated element only
200+
// inside an array; a bare returned element repeats its type and key.
201+
return [styleElement];
186202
}
187203
}
188204

0 commit comments

Comments
 (0)