|
| 1 | +--- |
| 2 | +title: createInitialModeExpression |
| 3 | +description: Creates a secure inline script to set the initial mode (light, dark, or system) before hydration. |
| 4 | +section: Utilities |
| 5 | +--- |
| 6 | + |
| 7 | +<script> |
| 8 | + import { Callout } from '@svecodocs/kit' |
| 9 | +</script> |
| 10 | + |
| 11 | +`createInitialModeExpression` outputs a small, inline JavaScript snippet as a string. |
| 12 | + |
| 13 | +It's typically used alongside server-rendered HTML and injected into the page head securely using SvelteKit's `transformPageChunk`. |
| 14 | + |
| 15 | +## When to Use |
| 16 | + |
| 17 | +Use `createInitialModeExpression` when: |
| 18 | + |
| 19 | +- You're operating under a Content Security Policy (CSP) that requires a `nonce` for inline scripts. |
| 20 | +- You're rendering the initial page via SvelteKit server hooks and want to inject logic at render time. |
| 21 | + |
| 22 | +This approach is ideal for security-sensitive environments or platforms with strict CSP headers, where inline scripts must include a trusted nonce. |
| 23 | + |
| 24 | +## Usage |
| 25 | + |
| 26 | +To use `createInitialModeExpression`, you need two things: |
| 27 | + |
| 28 | +### 1. Modify `app.html` |
| 29 | + |
| 30 | +Add the following placeholder in the `<head>` of your `app.html` file: |
| 31 | + |
| 32 | +```html title="app.html" |
| 33 | +<script nonce="%sveltekit.nonce%"> |
| 34 | + %modewatcher.snippet% |
| 35 | +</script> |
| 36 | +``` |
| 37 | + |
| 38 | +This placeholder will be replaced server-side at render time. |
| 39 | + |
| 40 | +### 2. Update `hooks.server.ts` |
| 41 | + |
| 42 | +Inject the snippet during SSR using `transformPageChunk`: |
| 43 | + |
| 44 | +```ts title="hooks.server.ts" |
| 45 | +import { createInitialModeExpression } from "mode-watcher"; |
| 46 | + |
| 47 | +export const handle: Handle = async ({ event, resolve }) => { |
| 48 | + return resolve(event, { |
| 49 | + transformPageChunk: ({ html }) => |
| 50 | + html.replace("%modewatcher.snippet%", createInitialModeExpression()), |
| 51 | + }); |
| 52 | +}; |
| 53 | +``` |
| 54 | + |
| 55 | +<Callout type="tip"> |
| 56 | + |
| 57 | +If you're planning to inject multiple types of initial client-side logic (e.g., directionality, locale), consider using a shared `%placeholder%` strategy with `transformPageChunk`. |
| 58 | + |
| 59 | +</Callout> |
| 60 | + |
| 61 | +## Credits |
| 62 | + |
| 63 | +Thanks to [@fnimick](https://github.com/fnimick) for contributing and validating this approach. |
0 commit comments