Skip to content

Commit 79cc7b4

Browse files
feat: add first-class CSP nonce support (#5693)
Add multiple ways to configure a CSP nonce for injected <style> tags: 1. StyleSheetManager nonce prop (recommended for Next.js, Remix) 2. ServerStyleSheet constructor nonce option (SSR) 3. <meta property="csp-nonce"> auto-detection (Vite convention) 4. <meta name="sc-nonce"> auto-detection (SC convention) 5. __webpack_nonce__ global (legacy, preserved for backward compat) The nonce flows through SheetOptions to makeStyleTag, ensuring all dynamically created style elements receive the nonce attribute. Based on PR #4356 by @ericsen-tsai. Closes #4258 Co-authored-by: Ericsen Tsai <[email protected]>
1 parent 89ec7a0 commit 79cc7b4

11 files changed

Lines changed: 249 additions & 22 deletions

File tree

‎.changeset/feat-nonce-support.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"styled-components": minor
3+
---
4+
5+
Add first-class CSP nonce support. Nonces can now be configured via `StyleSheetManager`'s `nonce` prop (recommended for Next.js, Remix), `ServerStyleSheet`'s constructor, `<meta property="csp-nonce">` (Vite convention), `<meta name="sc-nonce">`, or the legacy `__webpack_nonce__` global.

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

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,15 @@ export default class ServerStyleSheet {
1515
instance: StyleSheet;
1616
sealed: boolean;
1717

18-
constructor() {
19-
this.instance = new StyleSheet({ isServer: true });
18+
constructor({ nonce }: { nonce?: string } = {}) {
19+
this.instance = new StyleSheet({ isServer: true, nonce });
2020
this.sealed = false;
2121
}
2222

2323
_emitSheetCSS = (): string => {
2424
const css = this.instance.toString();
2525
if (!css) return '';
26-
const nonce = getNonce();
26+
const nonce = this.instance.options.nonce || getNonce();
2727
const attrs = [
2828
nonce && `nonce="${nonce}"`,
2929
`${SC_ATTR}="true"`,
@@ -66,7 +66,7 @@ export default class ServerStyleSheet {
6666
},
6767
};
6868

69-
const nonce = getNonce();
69+
const nonce = this.instance.options.nonce || getNonce();
7070
if (nonce) {
7171
(props as any).nonce = nonce;
7272
}

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ export type IStyleSheetManager = React.PropsWithChildren<{
6565
namespace?: undefined | string;
6666
/**
6767
* Create and provide your own `StyleSheet` if necessary for advanced SSR scenarios.
68+
* When provided, `target` and `nonce` props are ignored (configure them on the sheet directly).
6869
*/
6970
sheet?: undefined | StyleSheet;
7071
/**
@@ -89,6 +90,11 @@ export type IStyleSheetManager = React.PropsWithChildren<{
8990
* \* The plugin(s) must be compatible with stylis v4 or above.
9091
*/
9192
stylisPlugins?: undefined | stylis.Middleware[];
93+
/**
94+
* CSP nonce to attach to injected `<style>` tags. Overrides auto-detection
95+
* from `<meta name="sc-nonce">`, `<meta property="csp-nonce">`, or `__webpack_nonce__`.
96+
*/
97+
nonce?: undefined | string;
9298
/**
9399
* Provide an alternate DOM node to host generated styles; useful for iframes.
94100
*/
@@ -109,15 +115,17 @@ export function StyleSheetManager(props: IStyleSheetManager): React.JSX.Element
109115
if (props.sheet) {
110116
sheet = props.sheet;
111117
} else if (props.target) {
112-
sheet = sheet.reconstructWithOptions({ target: props.target }, false);
118+
sheet = sheet.reconstructWithOptions({ target: props.target, nonce: props.nonce }, false);
119+
} else if (props.nonce !== undefined) {
120+
sheet = sheet.reconstructWithOptions({ nonce: props.nonce });
113121
}
114122

115123
if (props.disableCSSOMInjection) {
116124
sheet = sheet.reconstructWithOptions({ useCSSOMInjection: false });
117125
}
118126

119127
return sheet;
120-
}, [props.disableCSSOMInjection, props.sheet, props.target, styleSheet]);
128+
}, [props.disableCSSOMInjection, props.nonce, props.sheet, props.target, styleSheet]);
121129

122130
const stylis = React.useMemo(
123131
() =>

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -641,4 +641,44 @@ describe('StyleSheetManager', () => {
641641
</style>
642642
`);
643643
});
644+
645+
it('should apply nonce to injected style tags', () => {
646+
const Comp = styled.div`
647+
color: red;
648+
`;
649+
650+
render(
651+
<StyleSheetManager nonce="test-nonce-123">
652+
<Comp />
653+
</StyleSheetManager>
654+
);
655+
656+
const style = document.head.querySelector('style[data-styled]');
657+
expect(style).not.toBeNull();
658+
expect(style!.getAttribute('nonce')).toBe('test-nonce-123');
659+
});
660+
661+
it('should apply different nonces to nested StyleSheetManagers', () => {
662+
const Outer = styled.div`
663+
color: blue;
664+
`;
665+
const Inner = styled.div`
666+
color: green;
667+
`;
668+
669+
render(
670+
<StyleSheetManager nonce="outer-nonce" target={document.head}>
671+
<Outer />
672+
<StyleSheetManager nonce="inner-nonce" target={document.body}>
673+
<Inner />
674+
</StyleSheetManager>
675+
</StyleSheetManager>
676+
);
677+
678+
const headStyle = document.head.querySelector('style[data-styled]');
679+
const bodyStyle = document.body.querySelector('style[data-styled]');
680+
681+
expect(headStyle!.getAttribute('nonce')).toBe('outer-nonce');
682+
expect(bodyStyle!.getAttribute('nonce')).toBe('inner-nonce');
683+
});
644684
});

‎packages/styled-components/src/sheet/Sheet.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ let SHOULD_REHYDRATE = IS_BROWSER;
1212

1313
type SheetConstructorArgs = {
1414
isServer?: boolean;
15+
nonce?: string | undefined;
1516
useCSSOMInjection?: boolean;
1617
target?: InsertionTarget | undefined;
1718
};

‎packages/styled-components/src/sheet/Tag.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ import { getSheet, makeStyleTag } from './dom';
33
import { SheetOptions, Tag } from './types';
44

55
/** Create a CSSStyleSheet-like tag depending on the environment */
6-
export const makeTag = ({ isServer, useCSSOMInjection, target }: SheetOptions) => {
6+
export const makeTag = ({ isServer, useCSSOMInjection, target, nonce }: SheetOptions) => {
77
if (isServer) {
88
return new VirtualTag(target);
99
} else if (useCSSOMInjection) {
10-
return new CSSOMTag(target);
10+
return new CSSOMTag(target, nonce);
1111
} else {
12-
return new TextTag(target);
12+
return new TextTag(target, nonce);
1313
}
1414
};
1515

@@ -20,8 +20,8 @@ export const CSSOMTag = class CSSOMTag implements Tag {
2020

2121
length: number;
2222

23-
constructor(target?: InsertionTarget | undefined) {
24-
this.element = makeStyleTag(target);
23+
constructor(target?: InsertionTarget | undefined, nonce?: string | undefined) {
24+
this.element = makeStyleTag(target, nonce);
2525

2626
// Avoid Edge bug where empty style elements don't create sheets
2727
this.element.appendChild(document.createTextNode(''));
@@ -63,8 +63,8 @@ export const TextTag = class TextTag implements Tag {
6363
nodes: NodeListOf<Node>;
6464
length: number;
6565

66-
constructor(target?: InsertionTarget | undefined) {
67-
this.element = makeStyleTag(target);
66+
constructor(target?: InsertionTarget | undefined, nonce?: string | undefined) {
67+
this.element = makeStyleTag(target, nonce);
6868
this.nodes = this.element.childNodes;
6969
this.length = 0;
7070
}

‎packages/styled-components/src/sheet/dom.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ const findLastStyleTag = (target: InsertionTarget): void | HTMLStyleElement => {
1111
};
1212

1313
/** Create a style element inside `target` or <head> after the last */
14-
export const makeStyleTag = (target?: InsertionTarget | undefined): HTMLStyleElement => {
14+
export const makeStyleTag = (
15+
target?: InsertionTarget | undefined,
16+
nonce?: string | undefined
17+
): HTMLStyleElement => {
1518
const head = document.head;
1619
const parent = target || head;
1720
const style = document.createElement('style');
@@ -21,9 +24,9 @@ export const makeStyleTag = (target?: InsertionTarget | undefined): HTMLStyleEle
2124
style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE);
2225
style.setAttribute(SC_ATTR_VERSION, SC_VERSION);
2326

24-
const nonce = getNonce();
27+
const resolvedNonce = nonce || getNonce();
2528

26-
if (nonce) style.setAttribute('nonce', nonce);
29+
if (resolvedNonce) style.setAttribute('nonce', resolvedNonce);
2730

2831
parent.insertBefore(style, nextSibling);
2932

‎packages/styled-components/src/sheet/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export interface GroupedTag {
2020

2121
export type SheetOptions = {
2222
isServer: boolean;
23+
nonce?: string | undefined;
2324
target?: InsertionTarget | undefined;
2425
useCSSOMInjection: boolean;
2526
};

‎packages/styled-components/src/test/ssr.test.tsx‎

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ import createGlobalStyle from '../constructors/createGlobalStyle';
1111
import ServerStyleSheet from '../models/ServerStyleSheet';
1212
import { StyleSheetManager } from '../models/StyleSheetManager';
1313

14-
jest.mock('../utils/nonce');
14+
jest.mock('../utils/nonce', () => {
15+
const mock = jest.fn(() => null);
16+
return { __esModule: true, default: mock, resetNonceCache: jest.fn() };
17+
});
1518

1619
let styled: ReturnType<typeof resetStyled>;
1720

@@ -48,7 +51,7 @@ describe('ssr', () => {
4851
beforeEach(() => {
4952
jest.spyOn(console, 'warn').mockImplementation(() => {});
5053

51-
require('../utils/nonce').mockReset();
54+
require('../utils/nonce').default.mockReset();
5255

5356
styled = resetStyled(true);
5457
});
@@ -142,7 +145,7 @@ describe('ssr', () => {
142145
});
143146

144147
it('should add a nonce to the stylesheet if webpack nonce is detected in the global scope', () => {
145-
require('../utils/nonce').mockImplementation(() => 'foo');
148+
require('../utils/nonce').default.mockImplementation(() => 'foo');
146149

147150
const Component = createGlobalStyle`
148151
body { background: papayawhip; }
@@ -216,7 +219,7 @@ describe('ssr', () => {
216219
});
217220

218221
it('should return a generated React style element with nonce if webpack nonce is preset in the global scope', () => {
219-
require('../utils/nonce').mockImplementation(() => 'foo');
222+
require('../utils/nonce').default.mockImplementation(() => 'foo');
220223

221224
const Component = createGlobalStyle`
222225
body { background: papayawhip; }
@@ -240,6 +243,64 @@ describe('ssr', () => {
240243
expect(element.props.nonce).toBe('foo');
241244
});
242245

246+
it('should use nonce from ServerStyleSheet constructor over auto-detection', () => {
247+
require('../utils/nonce').default.mockImplementation(() => 'auto-nonce');
248+
249+
const Heading = styled.h1`
250+
color: red;
251+
`;
252+
253+
const sheet = new ServerStyleSheet({ nonce: 'constructor-nonce' });
254+
renderToString(sheet.collectStyles(<Heading>Hello!</Heading>));
255+
256+
const css = sheet.getStyleTags();
257+
expect(css).toContain('nonce="constructor-nonce"');
258+
expect(css).not.toContain('auto-nonce');
259+
});
260+
261+
it('should use nonce from ServerStyleSheet constructor in getStyleElement', () => {
262+
const Heading = styled.h1`
263+
color: blue;
264+
`;
265+
266+
const sheet = new ServerStyleSheet({ nonce: 'element-nonce' });
267+
renderToString(sheet.collectStyles(<Heading>Hello!</Heading>));
268+
269+
const [element] = sheet.getStyleElement();
270+
expect(element.props.nonce).toBe('element-nonce');
271+
});
272+
273+
it('should fall back to auto-detection when no constructor nonce is provided', () => {
274+
require('../utils/nonce').default.mockImplementation(() => 'detected-nonce');
275+
276+
const Heading = styled.h1`
277+
color: green;
278+
`;
279+
280+
const sheet = new ServerStyleSheet();
281+
renderToString(sheet.collectStyles(<Heading>Hello!</Heading>));
282+
283+
const css = sheet.getStyleTags();
284+
expect(css).toContain('nonce="detected-nonce"');
285+
});
286+
287+
it('should omit nonce attribute when no nonce is available', () => {
288+
require('../utils/nonce').default.mockImplementation(() => null);
289+
290+
const Heading = styled.h1`
291+
color: purple;
292+
`;
293+
294+
const sheet = new ServerStyleSheet();
295+
renderToString(sheet.collectStyles(<Heading>Hello!</Heading>));
296+
297+
const css = sheet.getStyleTags();
298+
expect(css).not.toContain('nonce');
299+
300+
const [element] = sheet.getStyleElement();
301+
expect(element.props.nonce).toBeUndefined();
302+
});
303+
243304
describeStreamingTests('should interleave styles with rendered HTML', renderFn => {
244305
const Component = createGlobalStyle`
245306
body { background: papayawhip; }
Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,33 @@
11
declare let __webpack_nonce__: string;
22

3-
export default function getNonce() {
4-
return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
3+
/**
4+
* Resolve a CSP nonce from available sources (in priority order):
5+
* 1. <meta property="csp-nonce"> (Vite puts nonce in the `nonce` attr)
6+
* 2. <meta name="sc-nonce"> (SC convention, nonce in `content` attr)
7+
* 3. __webpack_nonce__ global (legacy)
8+
*
9+
* For Next.js/Remix, pass nonces explicitly via StyleSheetManager or
10+
* ServerStyleSheet instead—auto-detection doesn't apply to header-based nonces.
11+
*/
12+
let cached: string | undefined | false = false;
13+
14+
/** @internal Reset the nonce cache (for testing only). */
15+
export function resetNonceCache() {
16+
cached = false;
17+
}
18+
19+
export default function getNonce(): string | undefined {
20+
if (cached !== false) return cached;
21+
22+
if (typeof document !== 'undefined') {
23+
// Vite sets the nonce in the `nonce` attribute. Browsers expose this via
24+
// the .nonce DOM property but return "" from getAttribute('nonce').
25+
const viteMeta = document.head.querySelector<HTMLMetaElement>('meta[property="csp-nonce"]');
26+
if (viteMeta) return (cached = viteMeta.nonce || viteMeta.getAttribute('content') || undefined);
27+
28+
const scMeta = document.head.querySelector<HTMLMetaElement>('meta[name="sc-nonce"]');
29+
if (scMeta) return (cached = scMeta.getAttribute('content') || undefined);
30+
}
31+
32+
return (cached = typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : undefined);
533
}

0 commit comments

Comments
 (0)