Detailing theme toggle strategy with no-JS fallback
The plan combines SSR theme detection via URL param with a CSS :target hack using hidden anchors to enable no-JS toggling. The server sets a theme class on the main wrapper based on the query parameter, avoiding layout shifts on hydration by syncing the store initial state with this SSR value. For no-JS, clicking anchors with hashes like #theme-dark triggers CSS sibling selectors using :target to override theme variables dynamically, letting users toggle themes without JavaScript reloads. This hybrid approach ensures smooth theme toggling that gracefully falls back without JS while maintaining hydration consistency on the client.
Here's one way to wire it up in SvelteKit so that:
- All your components consume design tokens via CSS variables.
- The server renders the correct theme based on a
?theme= query or a default.
- When JS is off you can still flip the theme via a query string and/or a
:target fragment hack.
- When JS comes up, the store is initialised from the SSR value so there is no flash/layout shift on hydration.
The key ideas are:
- Put the entire app in a wrapper that you can skin with a
theme-light/theme-dark class.
- Define the same tokens on both the class and on
:target ~ .app so #theme-dark can also override without JS.
- Read the query param in
+layout.server.ts and pass it down; set the initial store from that.
- When you toggle with JS, update the store and the class; when you toggle without JS, follow a link that sets
?theme=… and/or #theme-….
Theme tokens (src/app.css)
/* Design system tokens */
:root {
--color-bg: white;
--color-fg: black;
--color-primary: rebeccapurple;
color-scheme: light;
}
/* Dark theme overrides */
.theme-dark {
--color-bg: #0d0d10;
--color-fg: #f5f6f7;
--color-primary: #6ab0ff;
color-scheme: dark;
}
/* Light theme class just there for symmetry */
.theme-light {
color-scheme: light;
}
/* No-JS :target fallback. Place #theme-dark/#theme-light before .app */
#theme-dark:target ~ .app {
--color-bg: #0d0d10;
--color-fg: #f5f6f7;
--color-primary: #6ab0ff;
color-scheme: dark;
}
#theme-light:target ~ .app {
--color-bg: white;
--color-fg: black;
--color-primary: rebeccapurple;
color-scheme: light;
}
/* Basic styles consuming the tokens */
body, .app {
margin: 0;
min-height: 100vh;
background: var(--color-bg);
color: var(--color-fg);
font-family: system-ui, sans-serif;
}
button {
background: var(--color-primary);
color: var(--color-bg);
border: none;
padding: 0.5rem 1rem;
border-radius: 9999px;
cursor: pointer;
}
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0,0,0,0);
white-space: nowrap;
border: 0;
}
Server load reads the theme (src/routes/+layout.server.ts)
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = ({ url }) => {
const param = url.searchParams.get('theme');
// Only allow known values
const theme = param === 'dark' ? 'dark' : 'light';
return { theme };
};
Theme store (src/lib/stores/theme.ts)
import { browser } from '$app/environment';
import { writable } from 'svelte/store';
const createThemeStore = (initial: 'light' | 'dark') => {
const { subscribe, set, update } = writable<'light' | 'dark'>(initial);
// Keep a data attribute on <html> in sync (optional)
if (browser) {
subscribe((value) => {
document.documentElement.dataset.theme = value;
document.documentElement.classList.toggle('theme-dark', value === 'dark');
document.documentElement.classList.toggle('theme-light', value === 'light');
});
}
return {
subscribe,
set,
toggle: () => update((t) => (t === 'light' ? 'dark' : 'light'))
};
};
export const theme = createThemeStore('light');
Layout applies initial theme and exposes fragment anchors (src/routes/+layout.svelte)
<script lang="ts">
import { onMount } from 'svelte';
import { theme } from '$lib/stores/theme';
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
export let data: { theme: 'light' | 'dark' };
// Initialise store from server data to avoid hydration mismatch
theme.set(data.theme);
// You can also set a class on the app wrapper via a local reactive var
$: currentTheme = data.theme;
$: $theme; // subscribe to store
onMount(() => {
// After hydration, sync the local theme class to the store
currentTheme = $theme;
});
</script>
<svelte:head>
<meta name="color-scheme" content="light dark" />
</svelte:head>
<!-- Hidden targets for :target hack -->
<a id="theme-light" class="visually-hidden">Light</a>
<a id="theme-dark" class="visually-hidden">Dark</a>
<div class={`app theme-${currentTheme}`}>
<header>
<h1>Design System</h1>
<ThemeToggle />
<noscript>
<div>
<!-- No-JS fallbacks: query param and fragment so both SSR and CSS hacks work -->
<a href="?theme=light#theme-light">Light theme</a> ·
<a href="?theme=dark#theme-dark">Dark theme</a>
</div>
</noscript>
</header>
<main>
<p>This text and the button use CSS variables from the design system.</p>
<button>Primary Action</button>
</main>
</div>
Theme toggle component (src/lib/components/ThemeToggle.svelte)
<script lang="ts">
import { browser } from '$app/environment';
import { get } from 'svelte/store';
import { theme } from '$lib/stores/theme';
let hrefDark = '';
let hrefLight = '';
if (browser) {
const url = new URL(window.location.href);
url.searchParams.set('theme', 'dark');
url.hash = 'theme-dark';
hrefDark = url.toString();
url.searchParams.set('theme', 'light');
url.hash = 'theme-light';
hrefLight = url.toString();
}
const toggle = () => theme.toggle();
</script>
{#if browser}
<!-- JS-enabled toggle -->
<button type="button" on:click={toggle}>
Switch to {get(theme) === 'light' ? 'dark' : 'light'} theme
</button>
{:else}
<!-- Render nothing; the <noscript> links in the layout handle no-JS -->
{/if}
How it works:
-
On the server, +layout.server.ts reads ?theme=dark and returns { theme: 'dark' }. The layout sets the wrapper class to theme-dark so the correct CSS variables are applied in the initial HTML. There is no flash because the server rendered HTML already has the right class.
-
The hidden <a id="theme-light"> and <a id="theme-dark"> before .app are the targets for the :target rules in app.css. With JS off, clicking a link to #theme-dark will match #theme-dark:target ~ .app and swap the variables.
-
The <noscript> block exposes two plain links. They include both the query string (so a full page reload will render the correct theme) and the fragment (so even without reload, the CSS hack works).
-
When JS loads, theme.set(data.theme) seeds the store with the SSR value so there is no mismatch. The store also keeps the <html> data attributes in sync if you want to use them.
All of your design system components should read colors, spacing, radii, etc. from the CSS variables; swapping theme-light/theme-dark (or targeting via the fragment hack) changes the tokens across the whole app.