Skip to content

Commit f4e439e

Browse files
authored
[Fizz] Add nonce to rendered import maps (#37339)
Apply the render's script nonce to import maps emitted through the `importMap` server rendering option. This keeps configured import maps compatible with nonce-based Content Security Policies and uses the same escaped nonce value as other render-managed scripts.
1 parent 0d69e20 commit f4e439e

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

‎packages/react-dom-bindings/src/server/ReactFizzConfigDOM.js‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,15 @@ export function createRenderState(
457457
const importMapChunks: Array<Chunk | PrecomputedChunk> = [];
458458
if (importMap !== undefined) {
459459
const map = importMap;
460-
importMapChunks.push(importMapScriptStart);
460+
importMapChunks.push(
461+
nonceScript === undefined
462+
? importMapScriptStart
463+
: stringToPrecomputedChunk(
464+
'<script type="importmap" nonce="' +
465+
escapeTextForBrowser(nonceScript) +
466+
'">',
467+
),
468+
);
461469
importMapChunks.push(
462470
stringToChunk(escapeEntireInlineScriptContent(JSON.stringify(map))),
463471
);

‎packages/react-dom/src/__tests__/ReactDOMFizzServer-test.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4520,6 +4520,40 @@ describe('ReactDOMFizzServer', () => {
45204520
);
45214521
});
45224522

4523+
it('applies the nonce option to the importmap script', async () => {
4524+
const importMap = {
4525+
foo: './path/to/foo.js',
4526+
};
4527+
await act(() => {
4528+
renderToPipeableStream(
4529+
<html>
4530+
<head>
4531+
<script async={true} src="foo" />
4532+
</head>
4533+
<body>
4534+
<div>hello world</div>
4535+
</body>
4536+
</html>,
4537+
{
4538+
importMap,
4539+
nonce: 'R4nd0m',
4540+
},
4541+
).pipe(writable);
4542+
});
4543+
4544+
expect(document.head.innerHTML).toBe(
4545+
'<script type="importmap" nonce="R4nd0m">' +
4546+
JSON.stringify(importMap) +
4547+
'</script><script async="" src="foo"></script>' +
4548+
(gate(flags => flags.shouldUseFizzExternalRuntime)
4549+
? '<script src="react-dom-bindings/src/server/ReactDOMServerExternalRuntime.js" async="" nonce="R4nd0m"></script>'
4550+
: '') +
4551+
(gate(flags => flags.enableFizzBlockingRender)
4552+
? '<link rel="expect" href="#_R_" blocking="render">'
4553+
: ''),
4554+
);
4555+
});
4556+
45234557
// bugfix: https://github.com/facebook/react/issues/27286
45244558
it('can render custom elements with children on ther server', async () => {
45254559
await act(() => {

0 commit comments

Comments
 (0)