Skip to content

Commit

Permalink
Some browsers, with some CSP configuration, will not preload a script…
Browse files Browse the repository at this point in the history
… if the prelaod link tag does not provide a valid nonce attribute. This change addes the ability to specify a nonce for `ReactDOM.preload(..., { as: "script" })`
  • Loading branch information
gnoff committed Jun 13, 2023
1 parent a7bf5ba commit 8ed2797
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2233,6 +2233,7 @@ function preloadPropsFromPreloadOptions(
crossOrigin: as === 'font' ? '' : options.crossOrigin,
integrity: options.integrity,
type: options.type,
nonce: options.nonce,
fetchPriority: options.fetchPriority,
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5532,6 +5532,7 @@ function preloadPropsFromPreloadOptions(
crossOrigin: as === 'font' ? '' : options.crossOrigin,
integrity: options.integrity,
type: options.type,
nonce: options.nonce,
fetchPriority: options.fetchPriority,
};
}
Expand Down
39 changes: 39 additions & 0 deletions packages/react-dom/src/__tests__/ReactDOMFloat-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3981,6 +3981,45 @@ body {
</html>,
);
});

it('supports nonce', async () => {
function App({url}) {
ReactDOM.preload(url, {as: 'script', nonce: 'abc'});
return 'hello';
}

await act(() => {
renderToPipeableStream(<App url="server" />).pipe(writable);
});

expect(getMeaningfulChildren(document)).toEqual(
<html>
<head />
<body>
<div id="container">
<link rel="preload" as="script" href="server" nonce="abc" />
hello
</div>
</body>
</html>,
);

ReactDOMClient.hydrateRoot(container, <App url="client" />);
await waitForAll([]);
expect(getMeaningfulChildren(document)).toEqual(
<html>
<head>
<link rel="preload" as="script" href="client" nonce="abc" />
</head>
<body>
<div id="container">
<link rel="preload" as="script" href="server" nonce="abc" />
hello
</div>
</body>
</html>,
);
});
});

describe('ReactDOM.preinit(href, { as: ... })', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/react-dom/src/shared/ReactDOMTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type PreloadOptions = {
crossOrigin?: string,
integrity?: string,
type?: string,
nonce?: string,
fetchPriority?: 'high' | 'low' | 'auto',
};
export type PreinitOptions = {
Expand Down

0 comments on commit 8ed2797

Please sign in to comment.