Skip to content

Commit 7831e15

Browse files
itisrmkdevin-ai-integration[bot]quantizor
authored
fix(rsc): keep >, quotes and & as written in server component styles on React 18 (#5881)
* fix(rsc): keep >, quotes and & as written in server component styles on React 18 React before 19 HTML-escapes <style> text children during server rendering, so Next.js 13.5 and 14 sent '.a &gt; .b' to the browser. Pass the CSS through dangerouslySetInnerHTML on those versions, with </style escaped as \3C/style; React 19 keeps text children. Fixes #5824. Co-Authored-By: Rahul Kashayp <[email protected]> * fix(rsc): gate React version check on IS_RSC, preserve case on closing-tag escape, and avoid spread allocation * fix(types): narrow StyleElementProps index signature for React.Attributes data-* augmentation * test(treeshake): pin browser DCE patterns against serverESM positive control --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Evan Jacobs <[email protected]>
1 parent 6aab68b commit 7831e15

9 files changed

Lines changed: 237 additions & 28 deletions

File tree

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+
Server component styles keep child combinators (`>`), quotes, and ampersands as written on Next.js 13.5 and 14, whose bundled React 18.3 canary HTML-escaped them inside the inline `<style>` tag (for example `.a &gt; .b`), so the browser dropped those rules on first load. A style value still cannot close the `<style>` tag. Next.js 15 and later were not affected and render the same output as before.

‎docs/rsc-style-injection.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ React Float only takes over a `<style>` carrying both `precedence` and `href`; a
99
an ordinary host element on the server and the client, attributes intact. The client renders the same
1010
element from the server-component payload, so it hydrates against the server HTML without a mismatch.
1111

12+
On React before 19 (Next.js 13.5 and 14's bundled React 18.3 canary, or any build whose
13+
`React.version` major is not `>= 19`), React's server renderer HTML-escapes `<style>` text children
14+
(`>` to `&gt;`, quotes, and `&`), which breaks CSS because browsers do not decode entities inside
15+
`<style>`. For those builds, `createStyleElement` in `src/utils/styleTagContent.ts` emits the CSS
16+
via `dangerouslySetInnerHTML` and escapes `</style` on the `s`/`S` (`</\73 tyle` / `</\53 tyle`) to
17+
block closing-tag breakout while preserving letter case and preceding backslashes (#5824). On React
18+
19+ (Next.js 15+), styles stay in plain `children` because React 19 writes `<style>` text raw and
19+
guards closing tags itself. The version check is gated on `IS_RSC`, so browser, standalone, and
20+
native builds eliminate it.
21+
1222
Inline body styles land after the registry's `<head>` styles in source order, so a cross-boundary
1323
extension (an RSC component extending a client component) wins the cascade. This placement is
1424
load-bearing, and `precedence` breaks it in four ways:

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import determineTheme from '../utils/determineTheme';
1010
import generateComponentId from '../utils/generateComponentId';
1111
import { joinRules, stripSplitter } from '../utils/joinStrings';
1212
import { createRSCCache } from '../utils/rscCache';
13+
import { createStyleElement } from '../utils/styleTagContent';
1314
import css from './css';
1415

1516
declare const __SERVER__: boolean;
@@ -186,11 +187,13 @@ export default function createGlobalStyle<Props extends object>(
186187
const styleKey = styledComponentId + '\n' + css;
187188
let styleElement = styleElements && styleElements.get(styleKey);
188189
if (!styleElement) {
189-
styleElement = React.createElement('style', {
190-
key: styledComponentId,
191-
'data-styled-global': styledComponentId,
192-
children: stripSplitter(css),
193-
});
190+
styleElement = createStyleElement(
191+
{
192+
key: styledComponentId,
193+
'data-styled-global': styledComponentId,
194+
},
195+
stripSplitter(css)
196+
);
194197
if (styleElements) styleElements.set(styleKey, styleElement);
195198
}
196199

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

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,35 @@ describe('createGlobalStyle RSC mode', () => {
150150
expect(resolved).toBe(fallback);
151151
});
152152

153+
it('keeps child combinators, quotes and ampersands as written on React before 19 (#5824)', () => {
154+
const GlobalStyle = createGlobalStyle`
155+
body > main::before {
156+
content: "a & b";
157+
}
158+
`;
159+
160+
const html = ReactDOMServer.renderToString(<GlobalStyle />);
161+
162+
expect(html).toContain('body>main::before{content:"a & b";}');
163+
expect(html).not.toMatch(/&(gt|quot|amp|#x27);/);
164+
});
165+
166+
it('does not let an interpolated value close the global style tag (#5824)', () => {
167+
const GlobalStyle = createGlobalStyle<{ $label: string }>`
168+
body::before {
169+
content: '${props => props.$label}';
170+
}
171+
`;
172+
173+
const html = ReactDOMServer.renderToString(
174+
<GlobalStyle $label="</style><script>alert(1)</script>" />
175+
);
176+
177+
expect(html.match(/<style\b/gi)).toHaveLength(1);
178+
expect(html.match(/<\/style/gi)).toHaveLength(1);
179+
expect(html).toContain("content:'</\\73 tyle><script>alert(1)</script>';");
180+
});
181+
153182
describe('shared style element (payload dedup)', () => {
154183
// The server-component payload writer encodes a repeated element object
155184
// once, so instances with identical CSS return one element while every
@@ -191,6 +220,13 @@ describe('createGlobalStyle RSC mode', () => {
191220
expect(renderOnce(GlobalStyle, { $bg: 'red' })).toBe(renderOnce(GlobalStyle, { $bg: 'red' }));
192221
});
193222

223+
const styleText = (
224+
el: React.ReactElement<{ children?: string; dangerouslySetInnerHTML?: { __html: string } }>
225+
) =>
226+
el.props.dangerouslySetInnerHTML
227+
? el.props.dangerouslySetInnerHTML.__html
228+
: el.props.children;
229+
194230
it('returns distinct element objects for different CSS, under one fixed key', () => {
195231
const GlobalStyle = createGlobalStyle<{ $bg: string }>`
196232
body { background: ${props => props.$bg}; }
@@ -200,8 +236,8 @@ describe('createGlobalStyle RSC mode', () => {
200236
const blue = renderOnce(GlobalStyle, { $bg: 'blue' });
201237

202238
expect(blue).not.toBe(red);
203-
expect(red.props.children).toBe('body{background:red;}');
204-
expect(blue.props.children).toBe('body{background:blue;}');
239+
expect(styleText(red)).toBe('body{background:red;}');
240+
expect(styleText(blue)).toBe('body{background:blue;}');
205241
expect(red.key).toMatch(/^sc-global-[\w-]+$/);
206242
expect(red.props['data-styled-global']).toBe(red.key);
207243
expect(blue.key).toBe(red.key);

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

Lines changed: 61 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,47 @@ describe('styled RSC mode', () => {
107107
});
108108
});
109109

110+
describe('style text on React before 19 (#5824)', () => {
111+
it('keeps child combinators, quotes and ampersands as written', () => {
112+
const List = styled.ul`
113+
& > li {
114+
color: red;
115+
}
116+
&::before {
117+
content: 'list & more';
118+
}
119+
&::after {
120+
content: "quoted's & raw";
121+
}
122+
`;
123+
124+
const css = extractStyleContents(ReactDOMServer.renderToString(<List />));
125+
126+
expect(css).toMatch(/\.\w+>li\{color:red;\}/);
127+
expect(css).toContain("content:'list & more';");
128+
expect(css).toContain('content:"quoted\'s & raw";');
129+
expect(css).not.toMatch(/&(gt|quot|amp|#x27);/);
130+
});
131+
132+
it('does not let an interpolated value close the style tag', () => {
133+
const Box = styled.div<{ $label: string }>`
134+
&::before {
135+
content: '${p => p.$label}';
136+
}
137+
`;
138+
139+
const html = ReactDOMServer.renderToString(
140+
<Box $label="</style><script>alert(1)</script>" />
141+
);
142+
143+
expect(countStyleTags(html)).toBe(1);
144+
expect(html.match(/<\/style/gi)).toHaveLength(1);
145+
expect(extractStyleContents(html)).toContain(
146+
"content:'</\\73 tyle><script>alert(1)</script>';"
147+
);
148+
});
149+
});
150+
110151
describe('base component CSS in RSC output (#5663)', () => {
111152
// In RSC mode, each component's CSS is retrieved via getGroup() which only
112153
// returns rules for that component's own group. When extending a base component,
@@ -435,8 +476,7 @@ describe('styled RSC mode', () => {
435476
const allCSS = extractStyleContents(html);
436477

437478
// Descendant/child combinators should have base class wrapped
438-
// renderToString HTML-encodes `>` as `&gt;`
439-
expect(allCSS).toMatch(/:where\(\.\w+\)&gt;span/);
479+
expect(allCSS).toMatch(/:where\(\.\w+\)>span/);
440480
expect(allCSS).toMatch(/:where\(\.\w+\) \.child/);
441481
expect(allCSS).not.toMatch(/:where\(\.\w+\)\{[^}]*padding:8px/);
442482
});
@@ -477,9 +517,8 @@ describe('styled RSC mode', () => {
477517
const html = ReactDOMServer.renderToString(<Extended />);
478518
const allCSS = extractStyleContents(html);
479519

480-
// renderToString HTML-encodes quotes (&#x27;)
481520
expect(allCSS).toMatchInlineSnapshot(
482-
`":where(.gpbfiF){background:url(&#x27;./bg.png&#x27;);}:where(.gpbfiF)::before{content:&#x27;.item&#x27;;}.inzFhn{color:red;}"`
521+
`":where(.gpbfiF){background:url('./bg.png');}:where(.gpbfiF)::before{content:'.item';}.inzFhn{color:red;}"`
483522
);
484523
expect(allCSS).not.toMatch(/:where\([^)]*\.item/);
485524
expect(allCSS).not.toMatch(/:where\([^)]*\.\/bg/);
@@ -881,7 +920,7 @@ describe('styled RSC mode', () => {
881920
const allCSS = extractStyleContents(html);
882921

883922
expect(allCSS).toMatchInlineSnapshot(
884-
`":where(.fizcbf){padding:8px;}:where(.fizcbf)::before{content:&#x27;.sc-something&#x27;;}.inzFhn{color:red;}"`
923+
`":where(.fizcbf){padding:8px;}:where(.fizcbf)::before{content:'.sc-something';}.inzFhn{color:red;}"`
885924
);
886925
expect(allCSS).not.toMatch(/:where\(\.\w+\)\{[^}]*color:red/);
887926
assertValidWhereSelectors(allCSS);
@@ -921,7 +960,7 @@ describe('styled RSC mode', () => {
921960
const allCSS = extractStyleContents(html);
922961

923962
expect(allCSS).toMatchInlineSnapshot(
924-
`":where(.cyCrZY){margin:4px;}:where(.cyCrZY)[data-value=&#x27;.foo&#x27;]{background:yellow;}.gnVozW{color:blue;}"`
963+
`":where(.cyCrZY){margin:4px;}:where(.cyCrZY)[data-value='.foo']{background:yellow;}.gnVozW{color:blue;}"`
925964
);
926965
assertValidWhereSelectors(allCSS);
927966
});
@@ -1116,7 +1155,7 @@ describe('styled RSC mode', () => {
11161155
const allCSS = extractStyleContents(html);
11171156

11181157
expect(allCSS).toMatchInlineSnapshot(
1119-
`":where(.iOeQph){margin:0;}:where(.iOeQph)::before{content:&#x27;\\2022&#x27;;}.esjoNE{padding:4px;}"`
1158+
`":where(.iOeQph){margin:0;}:where(.iOeQph)::before{content:'\\2022';}.esjoNE{padding:4px;}"`
11201159
);
11211160
expect(allCSS).not.toMatch(/:where\(\.\w+\)\{[^}]*padding:4px/);
11221161
assertValidWhereSelectors(allCSS);
@@ -1385,13 +1424,19 @@ describe('styled RSC mode', () => {
13851424
// as a server component runs, and reads the style element and element it
13861425
// returns; the HTML-level tag count is owned by "RSC per-instance style
13871426
// emission".
1427+
type StyleElement = React.ReactElement<{
1428+
children?: string;
1429+
dangerouslySetInnerHTML?: { __html: string };
1430+
}>;
13881431
type StyledOutput = React.ReactElement<{
1389-
children: [
1390-
React.ReactElement<{ children: string }>,
1391-
React.ReactElement<{ className: string }>,
1392-
];
1432+
children: [StyleElement, React.ReactElement<{ className: string }>];
13931433
}>;
13941434

1435+
const styleText = (el: StyleElement) =>
1436+
el.props.dangerouslySetInnerHTML
1437+
? el.props.dangerouslySetInnerHTML.__html
1438+
: el.props.children;
1439+
13951440
const renderStyled = (Component: unknown, props: object = {}) => {
13961441
const { render } = Component as {
13971442
render: (props: object, ref: null) => StyledOutput;
@@ -1472,7 +1517,7 @@ describe('styled RSC mode', () => {
14721517

14731518
const renderAlone = (Component: unknown) => {
14741519
mockCacheStore.clear();
1475-
return renderStyled(Component).styleElement.props.children;
1520+
return styleText(renderStyled(Component).styleElement);
14761521
};
14771522

14781523
it.each(['base first', 'extension first'])(
@@ -1494,8 +1539,8 @@ describe('styled RSC mode', () => {
14941539
const [base, ext] =
14951540
order === 'base first' ? [firstOutput, secondOutput] : [secondOutput, firstOutput];
14961541

1497-
expect(base.props.children).toBe(baseAlone);
1498-
expect(ext.props.children).toBe(extAlone);
1542+
expect(styleText(base)).toBe(baseAlone);
1543+
expect(styleText(ext)).toBe(extAlone);
14991544
expect(secondOutput).not.toBe(firstOutput);
15001545
}
15011546
);
@@ -1547,8 +1592,8 @@ describe('styled RSC mode', () => {
15471592
expect(a[1].styleElement).toBe(a[0].styleElement);
15481593
expect(b[1].styleElement).toBe(b[0].styleElement);
15491594
expect(b[0].styleElement).not.toBe(a[0].styleElement);
1550-
expect(a[0].styleElement.props.children).toContain(firstCSS);
1551-
expect(b[0].styleElement.props.children).toContain(secondCSS);
1595+
expect(styleText(a[0].styleElement)).toContain(firstCSS);
1596+
expect(styleText(b[0].styleElement)).toContain(secondCSS);
15521597
expect(b[0].element.props.className).not.toBe(a[0].element.props.className);
15531598
}
15541599
);

‎packages/styled-components/src/models/StyledComponent.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { joinStrings, stripSplitter } from '../utils/joinStrings';
3333
import merge from '../utils/mixinDeep';
3434
import { createRSCCache } from '../utils/rscCache';
3535
import { setToString } from '../utils/setToString';
36+
import { createStyleElement } from '../utils/styleTagContent';
3637
import ComponentStyle, { getCompiledCSSForName } from './ComponentStyle';
3738
import { useStyleSheetContext } from './StyleSheetManager';
3839
import { DefaultTheme, ThemeContext } from './ThemeProvider';
@@ -406,11 +407,13 @@ function useStyledComponentImpl<Props extends BaseObject>(
406407
if (!styleElement) {
407408
const combined = buildRSCStyleCSS(componentStyle, generatedClassName, ssc.styleSheet);
408409
if (combined) {
409-
styleElement = React.createElement('style', {
410-
[SC_ATTR]: '',
411-
key: 'sc-' + componentStyle.componentId,
412-
children: combined,
413-
});
410+
styleElement = createStyleElement(
411+
{
412+
[SC_ATTR]: '',
413+
key: 'sc-' + componentStyle.componentId,
414+
},
415+
combined
416+
);
414417
if (styleElements) styleElements.set(styleKey, styleElement);
415418
}
416419
}

‎packages/styled-components/src/test/treeshake.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,16 @@ describe('dead-code elimination: browser build', () => {
8585
expect(browserCJS).not.toContain('typeof React.createContext');
8686
});
8787

88+
it('eliminates RSC React.version check and style-tag escape', () => {
89+
const serverESM = read('styled-components.esm.js');
90+
expect(serverESM).toMatch(/parseInt\([^)]*\.version/);
91+
expect(serverESM).toContain('(s)(tyle)');
92+
expect(browserESM).not.toMatch(/parseInt\([^)]*\.version/);
93+
expect(browserCJS).not.toMatch(/parseInt\([^)]*\.version/);
94+
expect(browserESM).not.toContain('(s)(tyle)');
95+
expect(browserCJS).not.toContain('(s)(tyle)');
96+
});
97+
8898
it('exports createTheme', () => {
8999
expect(browserESM).toContain('createTheme');
90100
});
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import React from 'react';
2+
import { IS_RSC } from '../constants';
3+
4+
/**
5+
* React before 19 HTML-escapes the text children of a server-rendered `<style>`
6+
* (`>` becomes `&gt;`), and browsers never decode entities inside `<style>`, so
7+
* selectors and quoted values would break. Those versions get the CSS as raw
8+
* HTML instead, escaping the `s`/`S` of `</style` (`</\73 tyle` / `</\53 tyle`,
9+
* matching React 19's own emitter) so a value cannot close the tag while keeping
10+
* letter case and any preceding backslash intact. React 19 writes `<style>` text
11+
* raw and guards the closing tag itself.
12+
*
13+
* Gated on `IS_RSC` so browser, standalone, and native builds fold this to
14+
* `false` at build time; `!(>= 19)` fails safe to raw HTML when `React.version`
15+
* is missing or non-numeric.
16+
*/
17+
const REACT_ESCAPES_STYLE_TEXT = IS_RSC && !(parseInt(React.version, 10) >= 19);
18+
19+
type StyleElementProps = React.StyleHTMLAttributes<HTMLStyleElement> & Record<string, string>;
20+
21+
const escapeStyleTagClose = (_match: string, s: string, rest: string) =>
22+
(s === 'S' ? '</\\53 ' : '</\\73 ') + rest;
23+
24+
/** Creates a server-emitted `<style>` element with `css` attached safely for the active React version. */
25+
export function createStyleElement(props: StyleElementProps, css: string): React.ReactElement {
26+
if (REACT_ESCAPES_STYLE_TEXT) {
27+
props.dangerouslySetInnerHTML = {
28+
__html: css.replace(/<\/(s)(tyle)/gi, escapeStyleTagClose),
29+
};
30+
} else {
31+
props.children = css;
32+
}
33+
34+
return React.createElement('style', props);
35+
}

0 commit comments

Comments
 (0)