Allowing passing a nonce to inline-scripts/inline-styles to have better support for csp (#134)

Signed-off-by: alejandro <chen.alejandro97@protonmail.com>
This commit is contained in:
Chenalejandro 2024-07-16 17:16:29 -03:00 committed by GitHub
parent 66d0f704ff
commit a790dfa8de
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 20 additions and 6 deletions

View File

@ -1,7 +1,7 @@
"use client";
import { useLayoutEffect } from "react";
export function SsrScript(props: { script: string }) {
export function SsrScript(props: { script: string, nonce?: string }) {
useLayoutEffect(() => {
// TODO fix workaround: React has a bug where it doesn't run the script on the first CSR render if SSR has been skipped due to suspense
// As a workaround, we run the script in the <script> tag again after the first render
@ -9,5 +9,11 @@ export function SsrScript(props: { script: string }) {
(0, eval)(props.script);
}, []);
return <script dangerouslySetInnerHTML={{ __html: props.script }} />;
return (
<script
suppressHydrationWarning
nonce={props.nonce}
dangerouslySetInnerHTML={{ __html: props.script }}
/>
);
}

View File

@ -79,9 +79,11 @@ function convertColorsToCSS(theme: Theme) {
export function StackTheme({
theme,
children,
nonce,
} : {
theme?: ThemeConfig,
children?: React.ReactNode,
nonce?: string,
}) {
const themeValue: Theme = {
...DEFAULT_THEME,
@ -92,8 +94,14 @@ export function StackTheme({
return (
<StyledComponentsRegistry>
<BrowserScript />
<style dangerouslySetInnerHTML={{ __html: globalCSS + '\n' + convertColorsToCSS(themeValue) }} />
<BrowserScript nonce={nonce} />
<style
suppressHydrationWarning
nonce={nonce}
dangerouslySetInnerHTML={{
__html: globalCSS + "\n" + convertColorsToCSS(themeValue),
}}
/>
{children}
</StyledComponentsRegistry>
);

View File

@ -31,6 +31,6 @@ const script = () => {
});
};
export function BrowserScript() {
return <SsrScript script={`(${script.toString()})()`}/>;
export function BrowserScript(props : { nonce?: string }) {
return <SsrScript nonce={props.nonce} script={`(${script.toString()})()`}/>;
}