Skip to content

Commit ed7b199

Browse files
authored
fix(rsc): keep StyleSheetManager settings per request in server components (#5842)
* docs(rsc): scope StyleSheetManager settings per request and state the ordering contract * fix(rsc): scope StyleSheetManager settings to each request StyleSheetManager kept its RSC override and memoized stylis instance in module state, so a manager's plugins, namespace, or vendor prefixes could reach a later request. The override now lives in a React.cache slot per request, and the stylis memo is keyed on the plugins array, namespace, and enableVendorPrefixes. A namespace-only manager clears the memo so the next plugin manager rebuilds it. * test(rsc): assert exact per-request CSS, class names included * docs: add changeset for per-request StyleSheetManager settings * perf(rsc): make the per-request slot's creation the sheet reset, one cache lookup per render
1 parent 2a285ac commit ed7b199

4 files changed

Lines changed: 183 additions & 37 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"styled-components": patch
3+
---
4+
5+
Server components keep their `StyleSheetManager` settings when several requests render at the same time on one server. A server component that awaited data could lose settings such as `stylisPlugins` partway through its render, so `stylisPluginRSC` selectors like `:first-child` came out unrewritten at random under load.
6+
7+
A `StyleSheetManager` in server components that reuses the same `stylisPlugins` array no longer picks up the `namespace` or `enableVendorPrefixes` setting of another manager rendered before it.

‎docs/rsc-style-injection.md‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,22 @@ The Map lives behind `IS_RSC`, so browser builds drop it.
126126
tag, so stale CSS cannot accumulate across HMR cycles. Clearing `keyframeIds` is safe because
127127
components re-register keyframes through `keyframe.inject()` during render.
128128

129+
`mainSheet` is shared by every request in the process, so a concurrent request's reset can clear it
130+
mid-render. That is safe because each component compiles, registers and reads back its CSS for
131+
emission in one synchronous call.
132+
129133
## StyleSheetManager under RSC
130134

131-
`StyleSheetManager` works in RSC through a module-level `rscContextOverride` slot. Single-threaded RSC
132-
renders plus the per-render `React.cache` reset make this safe.
135+
RSC has no context, so `StyleSheetManager` writes its resolved settings into a request-scoped slot
136+
(`React.cache`) and styled components read that slot when they render. Concurrent requests on one
137+
server never see or clear each other's settings. A React build without `React.cache` falls back to one
138+
module-level slot with no reset, so a manager's settings carry into later requests.
139+
140+
The slot is not a scope. A manager's settings take effect when its body runs and apply to everything
141+
rendered after it in the same request, siblings outside the manager included. Next.js does not render
142+
shared layouts or templates on a client navigation, so a manager placed there does not reach the page
143+
in that request. A manager that must reach a page renders in that page, or in a component every page
144+
renders, before any await.
133145

134146
The override carries exactly four things: `shouldForwardProp`, `styleSheet`, `stylis` and
135147
`stylisPlugins`. A nested manager inherits `stylisPlugins` and `shouldForwardProp` from its parent
@@ -138,6 +150,10 @@ while keeping the outer plugins. Passing `stylisPlugins={[]}` explicitly opts ou
138150
the default stylis instance. When neither a custom stylis instance nor a `shouldForwardProp` survives
139151
resolution, the override is cleared to `null` rather than set to a redundant object.
140152

153+
The compiled stylis instance is memoized at module level, because the manager reads and writes it in
154+
one synchronous call. A memoized instance is reused only by a manager with the same plugins array
155+
(by identity), `namespace` and `enableVendorPrefixes`.
156+
141157
`nonce` is not part of that override. It is a sheet option, resolved by `getNonce()` in priority
142158
order: `<meta property="csp-nonce">` (Vite, which puts the value in the `nonce` attribute and exposes
143159
it only through the DOM property), then `<meta name="sc-nonce">` (the styled-components convention,

‎packages/styled-components/src/constructors/test/styled.rsc.test.tsx‎

Lines changed: 127 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,25 @@
66
// StyleSheetManager's per-render reset and, in dev, the redundant-emit-tag
77
// counter; see docs/rsc-style-injection.md)
88
const mockCacheStore = new Map<Function, any>();
9+
// The store React.cache reads at call time. Swapping it simulates a new request.
10+
let mockActiveStore = mockCacheStore;
911

1012
jest.mock('react', () => {
1113
const actual = jest.requireActual('react');
1214
return {
1315
...actual,
1416
cache: (fn: Function) => () => {
15-
if (!mockCacheStore.has(fn)) mockCacheStore.set(fn, fn());
16-
return mockCacheStore.get(fn);
17+
if (!mockActiveStore.has(fn)) mockActiveStore.set(fn, fn());
18+
return mockActiveStore.get(fn);
1719
},
1820
};
1921
});
2022

23+
/** Point React.cache at another request's store (a fresh Map starts a new request). */
24+
const mockUseRequest = (store: Map<Function, any>) => {
25+
mockActiveStore = store;
26+
};
27+
2128
// Mock IS_RSC before importing the module
2229
jest.mock('../../constants', () => ({
2330
...jest.requireActual('../../constants'),
@@ -43,6 +50,7 @@ const countStyleTags = (html: string): number => (html.match(/<style[^>]*>/g) ||
4350

4451
describe('styled RSC mode', () => {
4552
beforeEach(() => {
53+
mockActiveStore = mockCacheStore;
4654
mockCacheStore.clear();
4755
resetGroupIds();
4856
resetIdentifiers();
@@ -1708,6 +1716,123 @@ describe('styled RSC mode', () => {
17081716
});
17091717
});
17101718

1719+
describe('StyleSheetManager settings are scoped per request', () => {
1720+
const plugins = [stylisPluginRSC];
1721+
1722+
/** Render one element in a fresh request, so each render re-emits its own CSS. */
1723+
const renderFreshRequest = (element: React.ReactElement): string => {
1724+
mockUseRequest(new Map());
1725+
return extractStyleContents(ReactDOMServer.renderToString(element));
1726+
};
1727+
1728+
it('does not leak a manager from one request into another request', () => {
1729+
const requestA = new Map<Function, any>();
1730+
const Other = styled.li`
1731+
color: blue;
1732+
`;
1733+
const FirstChild = styled.li`
1734+
&:first-child {
1735+
color: red;
1736+
}
1737+
`;
1738+
1739+
mockUseRequest(requestA);
1740+
ReactDOMServer.renderToString(
1741+
React.createElement(StyleSheetManager, { stylisPlugins: plugins, children: null })
1742+
);
1743+
1744+
renderFreshRequest(React.createElement(Other, null, 'Other request'));
1745+
1746+
mockUseRequest(requestA);
1747+
const allCSS = extractStyleContents(
1748+
ReactDOMServer.renderToString(React.createElement(FirstChild, null, 'First'))
1749+
);
1750+
1751+
expect(allCSS).toMatchInlineSnapshot(
1752+
`".jxEASK:nth-child(1 of :not(style[data-styled])){color:red;}"`
1753+
);
1754+
});
1755+
1756+
it('drops a namespace when a later manager sets only plugins', () => {
1757+
const Item = styled.li`
1758+
&:first-child {
1759+
color: red;
1760+
}
1761+
`;
1762+
1763+
renderFreshRequest(
1764+
React.createElement(StyleSheetManager, {
1765+
stylisPlugins: plugins,
1766+
namespace: '.ns',
1767+
children: React.createElement(Item, null, 'A'),
1768+
})
1769+
);
1770+
const allCSS = renderFreshRequest(
1771+
React.createElement(StyleSheetManager, {
1772+
stylisPlugins: plugins,
1773+
children: React.createElement(Item, null, 'B'),
1774+
})
1775+
);
1776+
1777+
expect(allCSS).toMatchInlineSnapshot(
1778+
`".qMKal:nth-child(1 of :not(style[data-styled])){color:red;}"`
1779+
);
1780+
});
1781+
1782+
it('drops vendor prefixes when a later manager sets only plugins', () => {
1783+
const Item = styled.div`
1784+
user-select: none;
1785+
`;
1786+
1787+
renderFreshRequest(
1788+
React.createElement(StyleSheetManager, {
1789+
stylisPlugins: plugins,
1790+
enableVendorPrefixes: true,
1791+
children: React.createElement(Item, null, 'A'),
1792+
})
1793+
);
1794+
const allCSS = renderFreshRequest(
1795+
React.createElement(StyleSheetManager, {
1796+
stylisPlugins: plugins,
1797+
children: React.createElement(Item, null, 'B'),
1798+
})
1799+
);
1800+
1801+
expect(allCSS).toMatchInlineSnapshot(`".bGgXCC{user-select:none;}"`);
1802+
});
1803+
1804+
it('restores plugins when a namespace-only manager sits between two plugin managers', () => {
1805+
const Item = styled.li`
1806+
&:first-child {
1807+
color: red;
1808+
}
1809+
`;
1810+
1811+
renderFreshRequest(
1812+
React.createElement(StyleSheetManager, {
1813+
stylisPlugins: plugins,
1814+
children: React.createElement(Item, null, 'A'),
1815+
})
1816+
);
1817+
renderFreshRequest(
1818+
React.createElement(StyleSheetManager, {
1819+
namespace: '.ns',
1820+
children: React.createElement(Item, null, 'B'),
1821+
})
1822+
);
1823+
const allCSS = renderFreshRequest(
1824+
React.createElement(StyleSheetManager, {
1825+
stylisPlugins: plugins,
1826+
children: React.createElement(Item, null, 'C'),
1827+
})
1828+
);
1829+
1830+
expect(allCSS).toMatchInlineSnapshot(
1831+
`".qMKal:nth-child(1 of :not(style[data-styled])){color:red;}"`
1832+
);
1833+
});
1834+
});
1835+
17111836
describe('client reference proxy interpolation', () => {
17121837
/** Simulate a named-export client reference (typeof 'function', throws on call) */
17131838
function createNamedExportProxy(exportName: string) {

‎packages/styled-components/src/models/StyleSheetManager.tsx‎

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,28 @@ import { IS_RSC } from '../constants';
44
import StyleSheet from '../sheet';
55
import { InsertionTarget, ShouldForwardProp, Stringifier } from '../types';
66
import createStylisInstance from '../utils/stylis';
7+
import { createRSCCache } from '../utils/rscCache';
78

89
export const mainSheet: StyleSheet = new StyleSheet();
910
export const mainStylis: Stringifier = createStylisInstance();
1011

11-
/**
12-
* RSC context slot - module-level mutable state scoped per render via React.cache.
13-
* In RSC, createContext doesn't exist, so StyleSheetManager writes here and
14-
* useStyleSheetContext reads from here. Single-threaded RSC renders guarantee
15-
* no concurrent mutation. React.cache ensures reset between renders.
16-
*/
17-
let rscContextOverride: IStyleSheetContext | null = null;
12+
type RscSlot = { override: IStyleSheetContext | null };
13+
const rscFallbackSlot: RscSlot = { override: null };
14+
15+
/** Created once per server render; creating it is the per-render reset (see docs/rsc-style-injection.md). */
16+
const getRscSlot = createRSCCache((): RscSlot => {
17+
mainSheet.names.clear();
18+
mainSheet.keyframeIds.clear();
19+
mainSheet.clearTag();
20+
return { override: null };
21+
});
22+
const rscSlot = (): RscSlot => (getRscSlot ? getRscSlot() : rscFallbackSlot);
23+
1824
let rscLastPlugins: stylis.Middleware[] | undefined;
25+
let rscLastNamespace: string | undefined;
26+
let rscLastPrefix: boolean | undefined;
1927
let rscCachedStylis: Stringifier = mainStylis;
2028

21-
/** Per-render reset to prevent HMR accumulation (see docs/rsc-style-injection.md). */
22-
const ensureSheetReset: (() => void) | null = IS_RSC
23-
? (((React as any).cache as (<T extends (...args: any[]) => any>(fn: T) => T) | undefined)?.(
24-
() => {
25-
mainSheet.names.clear();
26-
mainSheet.keyframeIds.clear();
27-
mainSheet.clearTag();
28-
rscContextOverride = null;
29-
}
30-
) ?? null)
31-
: null;
32-
3329
export type IStyleSheetContext = {
3430
shouldForwardProp?: ShouldForwardProp<'web'> | undefined;
3531
styleSheet: StyleSheet;
@@ -63,12 +59,7 @@ export type IStylisContext = Stringifier | void;
6359
export function useStyleSheetContext() {
6460
if (!IS_RSC) return React.useContext(StyleSheetContext);
6561

66-
// Reset mainSheet once per render to prevent HMR accumulation.
67-
// React.cache ensures this runs exactly once per render, so calling
68-
// it here AND in StyleSheetManager is safe - whichever runs first wins.
69-
if (ensureSheetReset) ensureSheetReset();
70-
71-
return rscContextOverride || defaultContextValue;
62+
return rscSlot().override || defaultContextValue;
7263
}
7364

7465
export type IStyleSheetManager = React.PropsWithChildren<{
@@ -135,14 +126,11 @@ export type IStyleSheetManager = React.PropsWithChildren<{
135126

136127
/** Configure style injection for descendant styled components (target element, stylis plugins, prop forwarding). */
137128
export function StyleSheetManager(props: IStyleSheetManager): React.JSX.Element {
138-
// In RSC, context doesn't exist but we can set module-level state.
139-
// Single-threaded RSC renders + React.cache reset make this safe.
140129
if (IS_RSC) {
141-
// Reset once per render (React.cache scopes this per request)
142-
if (ensureSheetReset) ensureSheetReset();
130+
const slot = rscSlot();
143131

144132
// Merge with existing override: inherit parent values when props are omitted.
145-
const parentOverride = rscContextOverride || defaultContextValue;
133+
const parentOverride = slot.override || defaultContextValue;
146134

147135
// Build a stylis instance when any stylis-related prop is provided.
148136
// Cache it when the plugins array ref is stable.
@@ -152,8 +140,15 @@ export function StyleSheetManager(props: IStyleSheetManager): React.JSX.Element
152140
props.enableVendorPrefixes !== undefined;
153141

154142
if (hasStylisProps) {
155-
if (props.stylisPlugins && props.stylisPlugins !== rscLastPlugins) {
143+
if (
144+
props.stylisPlugins &&
145+
(props.stylisPlugins !== rscLastPlugins ||
146+
props.namespace !== rscLastNamespace ||
147+
props.enableVendorPrefixes !== rscLastPrefix)
148+
) {
156149
rscLastPlugins = props.stylisPlugins;
150+
rscLastNamespace = props.namespace;
151+
rscLastPrefix = props.enableVendorPrefixes;
157152
rscCachedStylis = createStylisInstance({
158153
options: { namespace: props.namespace, prefix: props.enableVendorPrefixes },
159154
plugins: props.stylisPlugins,
@@ -165,6 +160,9 @@ export function StyleSheetManager(props: IStyleSheetManager): React.JSX.Element
165160
options: { namespace: props.namespace, prefix: props.enableVendorPrefixes },
166161
plugins: props.stylisPlugins ?? parentOverride.stylisPlugins,
167162
});
163+
rscLastPlugins = undefined;
164+
rscLastNamespace = undefined;
165+
rscLastPrefix = undefined;
168166
}
169167
}
170168

@@ -179,14 +177,14 @@ export function StyleSheetManager(props: IStyleSheetManager): React.JSX.Element
179177
const resolvedPlugins = props.stylisPlugins ?? parentOverride.stylisPlugins;
180178

181179
if (resolvedStylis !== mainStylis || resolvedShouldForwardProp) {
182-
rscContextOverride = {
180+
slot.override = {
183181
shouldForwardProp: resolvedShouldForwardProp,
184182
styleSheet: mainSheet,
185183
stylis: resolvedStylis,
186184
stylisPlugins: resolvedPlugins,
187185
};
188186
} else {
189-
rscContextOverride = null;
187+
slot.override = null;
190188
}
191189

192190
return props.children as React.JSX.Element;

0 commit comments

Comments
 (0)