Skip to content

Commit f17f6c0

Browse files
authored
feat(rsc): add configureServerStyles to set plugins for every server component (#5865)
* fix(rsc): keep stylisPluginRSC's name through a production bundle * feat(rsc): add configureServerStyles to set plugins for every server component
1 parent 4bfc2cb commit f17f6c0

13 files changed

Lines changed: 426 additions & 42 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
---
2+
'styled-components': minor
3+
---
4+
5+
`configureServerStyles({ stylisPlugins })` sets the plugins every server component is styled with, for the whole server process. Call it once, at the top level of a module every server render loads first. In Next.js that's the root layout file:
6+
7+
```tsx
8+
// app/layout.tsx
9+
import { configureServerStyles, stylisPluginRSC } from 'styled-components';
10+
11+
configureServerStyles({ stylisPlugins: [stylisPluginRSC] });
12+
13+
export default function RootLayout({ children }: { children: React.ReactNode }) {
14+
// ...
15+
}
16+
```
17+
18+
It reaches every server-rendered page and nested layout, including pages prerendered at build time and pages reached by client-side navigation, which a `StyleSheetManager` in a shared layout does not reach. A `StyleSheetManager` in a server component starts from these plugins; its own `stylisPlugins` prop replaces them, and `stylisPlugins={[]}` drops them.
19+
20+
It applies to server components only. Client components take their plugins from a `StyleSheetManager` rendered on the client, such as the one in your style registry. Make one call per app: a later call replaces an earlier one and applies to renders that start after it.
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+
`stylisPluginRSC` keeps its name through a production bundle, so its class names match in development and production and it passes the plugin name check.

‎docs/rsc-style-injection.md‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -140,17 +140,18 @@ module-level slot with no reset, so a manager's settings carry into later reques
140140
The slot is not a scope. A manager's settings take effect when its body runs and apply to everything
141141
rendered after it in the same request, siblings outside the manager included. Next.js does not render
142142
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.
143+
in that request. Plugins for every page go in `configureServerStyles` (below). Any other setting that
144+
must reach a page goes in a manager that renders in that page, or in a component every page renders,
145+
before any await.
145146

146147
The override carries exactly four things: `shouldForwardProp`, `styleSheet`, `stylis` and
147148
`stylisPlugins`. A nested manager inherits `stylisPlugins` and `shouldForwardProp` from its parent
148149
when it omits them, which is what lets an inner manager set `namespace` or `enableVendorPrefixes`
149150
while keeping the outer plugins. Passing `stylisPlugins={[]}` explicitly opts out and falls back to
150-
the default stylis instance, or to a plugin-free instance that keeps a `namespace` or
151-
`enableVendorPrefixes` passed with it. When neither a custom stylis instance nor a
152-
`shouldForwardProp` survives resolution, the override is cleared to `null` rather than set to a
153-
redundant object.
151+
the default stylis instance, configured plugins included, or to a plugin-free instance that keeps a
152+
`namespace` or `enableVendorPrefixes` passed with it. When the resolved stylis instance is the server
153+
default and no `shouldForwardProp` survives resolution, the override is cleared to `null` rather
154+
than set to a redundant object.
154155

155156
The compiled stylis instance is memoized at module level, because the manager reads and writes it in
156157
one synchronous call. A memoized instance is reused only by a manager with the same plugins array
@@ -163,6 +164,24 @@ value in `content`), then the legacy `__webpack_nonce__` global. Header-based no
163164
Next.js and Remix, are not auto-detectable and must be passed explicitly to `StyleSheetManager` or
164165
`ServerStyleSheet`.
165166

167+
### configureServerStyles
168+
169+
- `configureServerStyles({ stylisPlugins })` sets the plugins every server component starts from,
170+
for the whole process, so they reach a page whose layout did not render in that request. With no
171+
override in the slot a read gets these defaults, and a manager inherits them like a nested manager
172+
inherits its parent's.
173+
- Stored on `globalThis` under a `Symbol.for` key that names the major version, and shape-checked on
174+
read, so every copy of the library in the process reads one value (Next bundles each server layer
175+
apart).
176+
- Last call wins. A call applies to renders that start after it, so it is a top-level statement in a
177+
module every server render loads first: in Next, the root layout file. Next runs
178+
`instrumentation.ts` only in the live server, never in the build workers that prerender static
179+
pages, so a call there misses every prerendered route.
180+
- One value per process: an app with several root layouts (route groups) makes one call, or each
181+
layout's call replaces the others' for every route.
182+
- Server components only: a process-wide value would differ between server rendering and the browser
183+
for client components. In the browser build the call does nothing and warns in development.
184+
166185
## Selectors broken by inline style tags
167186

168187
Inline `<style>` tags are real DOM children, so they perturb any selector that counts children or

‎packages/sandbox/app/layout.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import type { Metadata, Viewport } from 'next';
2-
import styled from 'styled-components';
2+
import styled, { configureServerStyles, stylisPluginRSC } from 'styled-components';
33
import StyledComponentsRegistry from './lib/registry';
44
import { CustomThemeProvider } from './components/theme-provider';
55
import { Sidebar } from './components/sidebar';
66
import theme from './lib/theme';
77

8+
configureServerStyles({ stylisPlugins: [stylisPluginRSC] });
9+
810
export const metadata: Metadata = {
911
title: 'styled-components RSC Test',
1012
description: 'Testing styled-components with React Server Components and Next.js 16',

‎packages/sandbox/app/rsc/layout.tsx‎

Lines changed: 0 additions & 6 deletions
This file was deleted.

‎packages/sandbox/app/rsc/page.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -446,8 +446,9 @@ export default function RSCTestPage() {
446446
RSC emits inline <Code>&lt;style&gt;</Code> tags as siblings of the styled element. These
447447
tags are real DOM children, so <Code>:first-child</Code>, <Code>:last-child</Code>, and{' '}
448448
<Code>:nth-child()</Code> would normally count them and produce wrong results. This page
449-
uses <Code>stylisPluginRSC</Code> via <Code>StyleSheetManager</Code> to rewrite these
450-
selectors automatically. Both columns should match.
449+
sets <Code>stylisPluginRSC</Code> for every server component with{' '}
450+
<Code>configureServerStyles()</Code> in the root layout to rewrite these selectors
451+
automatically. Both columns should match.
451452
</SectionDesc>
452453
<HintText>
453454
If broken: the <Code>:nth-child</Code> column colors don&apos;t match the{' '}

‎packages/styled-components/README.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,23 @@ const Card = styled.div`
188188
</ThemeProvider>
189189
```
190190

191+
### Plugins in server components
192+
193+
A `StyleSheetManager` in a server component applies to what renders after it in the same request, and Next.js does not re-render a shared layout on a client-side navigation. To give every server component the same plugins, call `configureServerStyles` once, at the top level of the root layout file:
194+
195+
```tsx
196+
// app/layout.tsx
197+
import { configureServerStyles, stylisPluginRSC } from 'styled-components';
198+
199+
configureServerStyles({ stylisPlugins: [stylisPluginRSC] });
200+
201+
export default function RootLayout({ children }: { children: React.ReactNode }) {
202+
// ...
203+
}
204+
```
205+
206+
The call is a plain statement, not a component, so it reaches every page, nested layout, and client-side navigation, including pages prerendered at build time. Make one call per app. A `StyleSheetManager` in a server component starts from these plugins; `stylisPlugins={[]}` drops them. Client components take their plugins from a `StyleSheetManager` rendered on the client.
207+
191208
### Shared styles with `css`
192209

193210
Extract reusable style blocks to share across components or apply conditionally.

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
StyleSheetConsumer,
1616
StyleSheetContext,
1717
StyleSheetManager,
18+
configureServerStyles,
1819
} from './models/StyleSheetManager';
1920
/* Import components */
2021
import ThemeProvider, { ThemeConsumer, ThemeContext, useTheme } from './models/ThemeProvider';
@@ -67,6 +68,7 @@ export {
6768
ThemeConsumer,
6869
ThemeContext,
6970
ThemeProvider,
71+
configureServerStyles,
7072
createGlobalStyle,
7173
createTheme,
7274
css,

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

Lines changed: 163 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,13 @@ import type { Middleware } from 'stylis';
3737
import { mainSheet } from '../../models/StyleSheetManager';
3838
import { resetGroupIds } from '../../sheet/GroupIDAllocator';
3939
import { resetIdentifiers } from '../../models/StyledComponent';
40-
import styled, { css, keyframes } from '../../index';
40+
import styled, {
41+
StyleSheetConsumer,
42+
configureServerStyles,
43+
createGlobalStyle,
44+
css,
45+
keyframes,
46+
} from '../../index';
4147
import {
4248
mainStylis,
4349
StyleSheetManager,
@@ -1885,6 +1891,162 @@ describe('styled RSC mode', () => {
18851891
});
18861892
});
18871893

1894+
describe('configureServerStyles', () => {
1895+
const REWRITTEN_FIRST_CHILD = ':nth-child(1 of :not(style[data-styled]))';
1896+
const configured = [stylisPluginRSC];
1897+
1898+
const makeItem = () => styled.li`
1899+
&:first-child {
1900+
color: red;
1901+
}
1902+
`;
1903+
1904+
const paintBlue: Middleware = Object.defineProperty(
1905+
(element => {
1906+
if (element.type === 'decl') element.return = 'color:blue;';
1907+
}) satisfies Middleware,
1908+
'name',
1909+
{ value: 'paint-blue' }
1910+
);
1911+
1912+
/** Render in a fresh request, with the generated class name (which hashes the plugins) replaced. */
1913+
const renderRequest = (element: React.ReactElement): string => {
1914+
mockUseRequest(new Map());
1915+
return extractStyleContents(ReactDOMServer.renderToString(element)).replace(
1916+
/\.[a-zA-Z0-9]+/g,
1917+
'.CLASS'
1918+
);
1919+
};
1920+
1921+
afterEach(() => {
1922+
configureServerStyles({ stylisPlugins: [] });
1923+
});
1924+
1925+
it('styles a request with no manager in it, as when a client navigation skips the layout', () => {
1926+
configureServerStyles({ stylisPlugins: configured });
1927+
const Item = makeItem();
1928+
1929+
expect(renderRequest(<Item />)).toBe(`.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`);
1930+
});
1931+
1932+
it('styles a global style', () => {
1933+
configureServerStyles({ stylisPlugins: configured });
1934+
const Global = createGlobalStyle`
1935+
li:first-child {
1936+
color: red;
1937+
}
1938+
`;
1939+
1940+
expect(renderRequest(<Global />)).toBe(`li${REWRITTEN_FIRST_CHILD}{color:red;}`);
1941+
});
1942+
1943+
it.each<[string, Record<string, unknown>, string]>([
1944+
['no props', {}, `.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`],
1945+
['only a namespace', { namespace: '#ns' }, `#ns .CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`],
1946+
[
1947+
'only enableVendorPrefixes',
1948+
{ enableVendorPrefixes: true },
1949+
`.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`,
1950+
],
1951+
[
1952+
'only shouldForwardProp',
1953+
{ shouldForwardProp: () => true },
1954+
`.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`,
1955+
],
1956+
])('keeps the configured plugins under a manager with %s', (_label, props, expected) => {
1957+
configureServerStyles({ stylisPlugins: configured });
1958+
const Item = makeItem();
1959+
1960+
expect(renderRequest(<StyleSheetManager {...props}>{<Item />}</StyleSheetManager>)).toBe(
1961+
expected
1962+
);
1963+
});
1964+
1965+
it('lets a manager replace the configured plugins', () => {
1966+
configureServerStyles({ stylisPlugins: configured });
1967+
const Item = makeItem();
1968+
1969+
expect(
1970+
renderRequest(
1971+
<StyleSheetManager stylisPlugins={[paintBlue]}>
1972+
<Item />
1973+
</StyleSheetManager>
1974+
)
1975+
).toBe('.CLASS:first-child{color:blue;}');
1976+
});
1977+
1978+
it('lets a manager drop the configured plugins with an empty list, for that request only', () => {
1979+
configureServerStyles({ stylisPlugins: configured });
1980+
const Item = makeItem();
1981+
1982+
expect(
1983+
renderRequest(
1984+
<StyleSheetManager stylisPlugins={[]}>
1985+
<Item />
1986+
</StyleSheetManager>
1987+
)
1988+
).toBe('.CLASS:first-child{color:red;}');
1989+
expect(renderRequest(<Item />)).toBe(`.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`);
1990+
});
1991+
1992+
it('reaches a request from a separate copy of the library, loaded into the same process', () => {
1993+
jest.isolateModules(() => {
1994+
const separateCopy: typeof import('../../index') = require('../../index');
1995+
1996+
expect(separateCopy.configureServerStyles).not.toBe(configureServerStyles);
1997+
separateCopy.configureServerStyles({ stylisPlugins: configured });
1998+
});
1999+
const Item = makeItem();
2000+
2001+
expect(renderRequest(<Item />)).toBe(`.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`);
2002+
});
2003+
2004+
it('uses the last call', () => {
2005+
configureServerStyles({ stylisPlugins: configured });
2006+
configureServerStyles({ stylisPlugins: [paintBlue] });
2007+
const Item = makeItem();
2008+
2009+
expect(renderRequest(<Item />)).toBe('.CLASS:first-child{color:blue;}');
2010+
});
2011+
2012+
it('styles later requests with a changed configuration', () => {
2013+
const Item = makeItem();
2014+
2015+
configureServerStyles({ stylisPlugins: configured });
2016+
expect(renderRequest(<Item />)).toBe(`.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`);
2017+
2018+
configureServerStyles({ stylisPlugins: [] });
2019+
expect(renderRequest(<Item />)).toBe('.CLASS:first-child{color:red;}');
2020+
});
2021+
2022+
it('rejects a plugin with no name on every request, never falling back to the earlier plugins', () => {
2023+
const Item = makeItem();
2024+
2025+
configureServerStyles({ stylisPlugins: configured });
2026+
expect(renderRequest(<Item />)).toBe(`.CLASS${REWRITTEN_FIRST_CHILD}{color:red;}`);
2027+
2028+
configureServerStyles({ stylisPlugins: [() => {}] });
2029+
expect(() => renderRequest(<Item />)).toThrow();
2030+
expect(() => renderRequest(<Item />)).toThrow();
2031+
});
2032+
2033+
it('gives StyleSheetConsumer the configured plugins', () => {
2034+
configureServerStyles({ stylisPlugins: configured });
2035+
let seen: unknown;
2036+
2037+
renderRequest(
2038+
<StyleSheetConsumer>
2039+
{context => {
2040+
seen = context.stylisPlugins;
2041+
return null;
2042+
}}
2043+
</StyleSheetConsumer>
2044+
);
2045+
2046+
expect(seen).toBe(configured);
2047+
});
2048+
});
2049+
18882050
describe('client reference proxy interpolation', () => {
18892051
/** Simulate a named-export client reference (typeof 'function', throws on call) */
18902052
function createNamedExportProxy(exportName: string) {

0 commit comments

Comments
 (0)