CSP
ColorSchemeScript runs an inline script before the first paint. Allow it under a Content-Security-Policy (CSP) with a nonce or a hash.
On this page
Behavior when blocked
The browser does not run a script the policy has not allowed, and reports the violation in the console. After hydration the provider’s effect puts the class on, so the page ends up in the right scheme.
Until then <html> has no dark class, so the page is painted light. A visitor who gets dark briefly sees the light scheme. Even with themeColor, no theme-color <meta> is written.
Pitfall
'unsafe-inline' makes it run, along with every other inline script that reaches the page. Allow only this script, by nonce or hash.
Allowing by nonce
src/routes/layout.tsximport {
ColorSchemeProvider,
ColorSchemeScript,
} from '@k8ordo/color-scheme';
import { nonce } from '@k8ordo/framework/server';
import type { ReactNode } from 'react';
export default function RootLayout({
children,
}: {
children: ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<ColorSchemeScript nonce={nonce()} />
The per-response nonce, the same value the policy names
</head>
<body>
<ColorSchemeProvider>{children}</ColorSchemeProvider>
</body>
</html>
);
}Pass the nonce the policy names to ColorSchemeScript’s nonce prop. The script gets it as its nonce attribute and runs under script-src 'nonce-…'.
For the policy in @k8ordo/framework’s server mode, see CSP in @k8ordo/framework.
Allowing by hash
import { colorSchemeScriptHash } from '@k8ordo/color-scheme';
const policy = `script-src 'self' ${await colorSchemeScriptHash()}`;colorSchemeScriptHash() returns the script’s SHA-256 as a CSP source, 'sha256-…'. The return value is a Promise, so await it. When a page has no per-response nonce, such as a page served as a static file, put this value in script-src.
Compute the hash in the code that builds the policy, every time, rather than copying its value. The script’s text is the installed version’s, and an update may change it.
For the csp option of framework() in static mode, see CSP in @k8ordo/framework.
Props and the hash
src/routes/layout.tsx<head>
<ColorSchemeScript
defaultPreference="dark"
themeColor={themeColor}
/>
</head>
<body>
<ColorSchemeProvider defaultPreference="dark">
{children}
</ColorSchemeProvider>
</body>const hash = await colorSchemeScriptHash({
defaultPreference: 'dark',
themeColor,
});
const policy = `script-src 'self' ${hash}`;The default and the themeColor colors are written into the script, so each value gives a different hash. When ColorSchemeScript is given a defaultPreference or a themeColor, give colorSchemeScriptHash() the same values.
A policy that allows the script by nonce does not change with the default or the colors.