Design a Theme Switcher – Frontend System Design

We’ll walk through the frontend system design for theming and dark mode in a large web app with a shared design system. You’ll see how design tokens are layered so a theme only changes one tier, why CSS custom properties are the runtime switch, how light, dark, and system preferences resolve into one active theme, and how to put the right theme on the very first frame instead of flashing white at a user who asked for dark.
The interviewer usually phrases it as “design changing the theme of a page”. A toggle that flips a class takes five minutes. The real question is everything around it: 300 components that must not hardcode colors, server rendering that doesn’t know the OS setting, charts drawn on canvas, 20 customer brands, and a WCAG audit at the end.
Problem Statement
Design theming for a large web application and its component library.
Requirements:
- Users can choose light, dark, or follow the system setting
- The page renders in the correct theme on first paint, with no flash
- The choice persists across reloads, tabs, and signed-in devices
- Enterprise customers get their own brand colors in both light and dark
- Charts, canvas, images, and native form controls follow the theme
- Every theme meets WCAG contrast and works in high contrast modes
Describe the token model, the runtime mechanism, first-paint strategy, and how preferences sync.
Interviewers are checking three things. Do you separate what a color is from what it is for? Do you understand the browser’s loading sequence well enough to explain why a flash happens and exactly where to stop it? And do you treat accessibility as a constraint on the token system, not a checkbox after launch?
Clarifying Questions
| # | Question | Interviewer’s Answer |
|---|---|---|
| 1 | Which themes ship on day one? | Light, dark, and “system”. High contrast is a follow-up. |
| 2 | How is the app rendered? | SSR for the signed-in app. Marketing and docs are static HTML on a CDN. |
| 3 | Is there white-labeling? | Yes. About 20 enterprise tenants, each on its own subdomain with its own brand colors. |
| 4 | Should the choice follow the user across devices? | Yes for signed-in users. Anonymous visitors are per device. |
| 5 | Can parts of a page use a different theme? | Yes. Code samples and the video player are always dark. |
| 6 | Do we draw anything outside the DOM? | Dashboards use canvas charts. Some illustrations are SVG. |
| 7 | Browser support? | Evergreen Chrome, Edge, Firefox, and Safari 16+. |
Question 2 decides the first-paint strategy. SSR pages can read a cookie, but CDN-cached static pages are identical for everyone, so they need a client-side fix that still runs before paint. Question 3 means brand and mode are two independent dimensions, so tokens must compose instead of multiplying into 40 stylesheets. Question 5 rules out any design that assumes one theme per document.
Requirements
Functional
- A theme menu with three options: light, dark, system. System is the default.
- When the preference is system, the page follows OS changes live, for example when macOS switches to dark at sunset.
- A change applies instantly in the current tab, in other open tabs, and on the user’s other signed-in devices.
- Tenant brand colors apply on their subdomain in both modes.
- Any subtree can opt into a fixed theme with an attribute.
- Native controls (scrollbars, checkboxes, date pickers, autofill) match the active theme.
Non-Functional
- Zero frames painted in the wrong theme, on SSR and on cached static pages.
- Switching themes costs less than one frame of main-thread work on a mid-range laptop and does not animate every color on the page.
- Theme CSS adds less than 5 KB gzipped to the critical path.
- Text meets 4.5:1 contrast and UI components meet 3:1, in every theme and brand.
- Components never reference raw colors. A lint rule enforces it.
“Zero wrong frames” is the requirement that shapes the design. It means the theme must be known before the browser paints anything, which pushes the decision out of React and into the HTML response or the <head>.
Napkin Math
| Metric | Estimate | Calculation | So what? |
|---|---|---|---|
| CSS for both modes | ~13.5 KB raw, ~3 KB gzip | 150 semantic tokens × 2 modes × ~45 bytes | Ship dark in the main stylesheet. Lazy-loading it saves less than one icon. |
| One brand sheet | ~3.6 KB raw | 40 overridden tokens × 2 modes × ~45 bytes | Load only the tenant’s sheet, never all 20 (~72 KB). |
| Inline head script | ~300–500 bytes | Read one key, set one attribute | Fits easily in the first ~14 KB round trip (10 segments × 1,460 bytes). |
| Flash without a fix | ~1.6 s, ~96 frames | Hydration at 2.8 s minus first paint at 1.2 s, at 60Hz | A client-only effect is not a fix. Even one wrong frame is visible. |
| Elements restyled on switch | All of them, ~5,000 | Attribute on <html> invalidates every descendant |
Unavoidable. Keep selectors simple and transitions off. |
| Theme cookie overhead | ~11 bytes per request | theme=dark plus a separator |
Free. The cache cost of varying HTML on it is not. |
Architecture
The system has a build-time half and a runtime half. Tokens are authored once as data, compiled into CSS, and at runtime one attribute on <html> decides which block of variables applies.
| Layer | Owns | Runs | Talks to |
|---|---|---|---|
| Token source + build | Token JSON, alias resolution, contrast lint, TS types | CI | CDN (hashed CSS), component code (types) |
| SSR / Edge | Reading the theme cookie and host, writing data-theme |
Every HTML request | Preferences API, browser |
| Head script | Filling in the theme on cached HTML | Before <body> parses |
localStorage, <html> |
| ThemeController | Preference, resolution, persistence, events | Client singleton | Theme menu, storage, profile API, subscribers |
| Consumers | Components via var(), charts via getComputedStyle |
Render and paint | CSS cascade, controller |
Notice what is missing: there is no React context holding colors. React never re-renders when the theme changes. The browser’s cascade does the work, which is faster and also works for markup React doesn’t own.
“The theme is one attribute on the root element. CSS variables do the switching, so a theme change is a style recalculation, not a re-render. JavaScript only owns the preference.”
If the interviewer asks why not CSS-in-JS with a theme object in context: runtime CSS-in-JS regenerates class names and injects new rules when the theme prop changes, and every styled component re-renders. With variables, the generated CSS is identical across themes and only the variable values change.
Data Model
Tokens come in three tiers, and the discipline that makes theming cheap is that each tier may only reference the tier directly below it.
| Tier | Example | Changes per theme? | Who uses it |
|---|---|---|---|
| Primitive | blue.600 = #2563eb |
No (brands may override) | Only semantic tokens |
| Semantic | color.action.primary |
Yes: one alias per mode | Component tokens, app CSS |
| Component | button.primary.bg |
No: aliases a semantic token | One component |
The semantic tier is the theming contract. Dark mode is not “invert the palette”. It is a second column of aliases: color.bg.surface points at gray.0 in light and gray.950 in dark. Adding a high contrast theme adds a third column. No component changes.
export type Mode = "light" | "dark";
export type ThemePreference = Mode | "system";
export type Contrast = "standard" | "more";
type Alias = `{${string}}`; // "{blue.600}"
interface PrimitiveToken {
readonly name: string; // "blue.600"
readonly $type: "color" | "dimension" | "duration";
readonly $value: string; // "#2563eb"
}
interface SemanticToken {
readonly name: string; // "color.action.primary"
readonly $type: "color";
readonly light: Alias;
readonly dark: Alias;
readonly highContrast?: Alias;
readonly description: string;
}
interface ComponentToken {
readonly name: string; // "button.primary.bg"
readonly $value: Alias; // must point at a semantic token
readonly component: string;
}
interface BrandTokenSet {
readonly brandId: string;
readonly primitives: Readonly<Record<string, string>>;
readonly semantic: Readonly<Record<string, Partial<Record<Mode, Alias>>>>;
readonly cssUrl: string; // "/brands/acme.3fa2.css"
}
interface StoredPreference {
readonly theme: ThemePreference;
readonly contrast: Contrast;
readonly updatedAt: string; // server-assigned ISO time
}
Three choices are worth defending.
Store the preference, derive the theme. The user picked “system”, not “dark”. If you store the resolved value, the app stops following the OS the first time it saves. Only StoredPreference is persisted. The active mode is recomputed from it plus prefers-color-scheme.
The $type / $value shape. This is the W3C Design Tokens Community Group format. Using it means design tools and token build tools can read the same file, so designers and engineers edit one source of truth.
Brands override primitives, rarely semantics, never components. A brand says “our blue is #0a66c2” and maybe “our primary action uses brand teal”. It never says “buttons have 6px radius in our theme”, because that would fork the component library per tenant.
Tokens as CSS Custom Properties
CSS custom properties are the right runtime mechanism for one reason: they inherit and they are resolved at style time. Sass variables are compiled away, so switching would mean shipping and swapping whole stylesheets. Custom properties let one stylesheet hold every theme, and an attribute selector picks which values apply.
/* Tier 1: primitives. Never referenced by components. */
:root { --gray-0: #ffffff; --gray-950: #020617; --blue-400: #60a5fa; --blue-600: #2563eb; }
/* Tier 2: semantic, one block per mode. */
:root, [data-theme="light"] { color-scheme: light; --color-bg-surface: var(--gray-0); --color-action-primary: var(--blue-600); }
[data-theme="dark"] { color-scheme: dark; --color-bg-surface: var(--gray-950); --color-action-primary: var(--blue-400); }
/* "system" means no attribute: follow the OS with zero JavaScript. */
@media (prefers-color-scheme: dark) { :root:not([data-theme]) { /* same values as the dark block */ } }
Tier 3, component tokens like --button-bg, are declared on the component’s own selector and point at a semantic token. The same generated stylesheet also carries two small utility rules used only during a switch: one that disables transitions while a theme-switching class is on the root, and one that turns off the default View Transitions cross-fade.
Two details in that stylesheet separate a working design from a buggy one.
“System” is the absence of an attribute. The selector :root:not([data-theme]) inside the media query means a user on system needs no JavaScript at all. The browser re-evaluates the media query the instant the OS flips. The dark block is duplicated in the output, but the build generates it, so nobody maintains it twice.
Component tokens must not be declared on :root. A custom property whose value contains var() is resolved on the element that declares it, and descendants inherit the resolved value. If you write :root { --button-bg: var(--color-action-primary) }, every button inherits the root’s light blue, even inside a data-theme="dark" section. Declare component tokens on the component selector so they resolve where the button actually is.
The color-scheme property
Your tokens only color your CSS. Scrollbars, checkboxes, <select> popups, date pickers, and autofill backgrounds are drawn by the browser. The color-scheme property tells it which palette to use for them, per element, which is why each token block sets it.
Add <meta name="color-scheme" content="light dark"> to the head as well. It declares, before any CSS arrives, that the page supports both schemes, so the browser can pick a matching default canvas background and form-control palette from the start.
With color-scheme set per scope, the newer CSS function light-dark(#fff, #020617) picks a value based on the element’s used color scheme. It is a compact way to write semantic tokens, but Safari only added it in 17.5, and our support matrix starts at Safari 16. Keep the attribute blocks. They also scale to a third mode like high contrast, while light-dark() only has two slots.
Nested themes
Because the token blocks use [data-theme="dark"] rather than :root[data-theme="dark"], any element can start a new theme scope. The code sample block sets data-theme="dark", its custom properties are redefined there, and every descendant inherits them. Nested light inside dark works too, which is why the light block also matches [data-theme="light"] and not just :root.
Nested scopes are also why consumers that read tokens in JavaScript must read them from their own element, not from document.documentElement.
Token build pipeline
Never hand-write that CSS. The build reads token JSON, resolves aliases into var() references, emits one block per mode, generates TypeScript types, and fails CI on contrast violations.
type Alias = `{${string}}`;
type Mode = "light" | "dark";
interface TokenSource {
readonly primitives: Readonly<Record<string, string>>;
readonly semantic: Readonly<Record<string, Readonly<Record<Mode, Alias>>>>;
readonly contrastPairs: readonly (readonly [fg: string, bg: string, min: number])[];
}
The build is a pure function of that source, with three outputs.
- CSS. Each token path becomes a custom property name (
color.bg.surfacebecomes--color-bg-surface). Each alias becomes avar()reference, so the cascade does the resolution at runtime. It emits the primitives block, the light and dark blocks, and the media-query copy of the dark block. - Types. A
SemanticTokenstring union of every semantic key. - Contrast report. For every declared pair and every mode, resolve both tokens to hex, compute the WCAG 2.x contrast ratio from relative luminance, and fail if it is below the minimum. An alias that doesn’t resolve is a build error, not a silent fallback.
The generated SemanticToken union powers a typed helper like token("color.bg.surface") for CSS-in-TS and inline styles, so a typo is a compile error. A lint rule bans hex values and primitive variables in component CSS, which is what keeps the tiers honest over years.
The contrast pairs are declared next to the tokens: ["color.text.primary", "color.bg.surface", 4.5], ["color.border.input", "color.bg.surface", 3]. The same lint runs against every brand set, which catches a tenant whose chosen yellow fails on white before it ships.
Avoiding the Flash of Incorrect Theme
The flash (sometimes called FART, a flash of inaccurate color theme) has one cause: the browser painted before anything told it the theme. The common mistake is reading localStorage in a useEffect. Effects run after hydration, which on a mid-range phone can be more than a second after first paint. Every frame in between uses the default light tokens.
The fix is to decide the theme before first paint. There are two places that can happen, and a large app uses both.
Path A: SSR reads a cookie
When the user changes the theme, the controller writes a theme cookie alongside localStorage. The server reads it on every HTML request and renders <html data-theme="dark"> directly. The very first byte of markup is already correct.
The server side is two small functions in the HTML renderer. One reads the theme cookie from the request header and returns "light", "dark", or null. Anything else, including "system", a missing cookie, or a tampered value, is null. The other builds the opening <html> tag with data-brand and, only when the theme is explicit, data-theme.
Three rules matter here. The cookie value goes through an allowlist, never straight into HTML, because cookies are user-controlled input. “System” renders no attribute, so the CSS media query handles it. And brandId comes from the server’s own host-to-tenant map, not from the request.
The server can’t see the OS setting by default. Chromium browsers support the Sec-CH-Prefers-Color-Scheme client hint if you send Accept-CH: Sec-CH-Prefers-Color-Scheme, but you rarely need it: with the no-attribute rule, CSS resolves “system” on its own. Use the hint only when the server must produce theme-specific bytes, like a server-rendered chart image.
The cost is caching. HTML that depends on a cookie can’t be shared across users at the CDN. That is fine for the signed-in app, where HTML is already Cache-Control: private. It is not fine for marketing pages.
Path B: a tiny blocking script in the head
Static pages are byte-for-byte identical for everyone, so the fix must run in the browser, before paint. That is exactly what a classic inline script in <head> does.
The head is ordered on purpose: <meta charset>, the color-scheme meta tag, then a classic inline script carrying a CSP nonce, then the token and brand stylesheets. The script does one thing. It reads theme from localStorage inside a try. If the value is "light" or "dark", it sets data-theme on the root. If it is "system", it removes the attribute. Anything else leaves the markup alone.
Every property of the script is deliberate.
- Inline, not
src. An external script needs a network fetch, and a parser-blocking one would stall the whole page on it. Inline code runs with zero round trips. - Classic and blocking, not
defer,async, ortype="module". Those run after parsing or whenever they arrive, which can be after first paint. A classic inline script runs the moment the parser reaches it, before any<body>content exists. - Before the stylesheets. A parser-blocking script placed after a pending stylesheet waits for that stylesheet to download. Placing it first lets it run immediately.
- Wrapped in
try.localStoragethrows when storage is disabled or blocked, for example in some sandboxed iframes. A failure must fall back to system, not break the page. - Tiny. It blocks parsing, so it does one read and one attribute write. No framework, no imports.
On SSR pages the same script still runs. It is a no-op when the attribute already matches, and it corrects the case where the cookie is missing or stale, for example after the user cleared cookies but not site storage.
Content Security Policy
A strict CSP blocks inline scripts. You have two ways to allow this one. For SSR responses, generate a random nonce per response, put it in Content-Security-Policy: script-src 'nonce-R4nd0mPerResponse', and on the tag. For static cached HTML a per-response nonce is impossible, so allow the script by hash: script-src 'sha256-...' computed from its exact text at build time. Never fall back to 'unsafe-inline' to make the theme work.
Hydration mismatch
If the head script changes an attribute on <html> that React also renders, React warns that server and client markup differ. Put suppressHydrationWarning on the <html> element. It only suppresses attribute mismatches on that one element, which is exactly the scope you want.
The deeper rule: never branch markup on the theme. If a component renders a different <img> or class name for dark, the server and a system-preference client disagree. Let CSS choose. JavaScript only needs the resolved theme for canvas and third-party widgets.
| Strategy | Wrong frames | CDN-cacheable HTML | Needs JS |
|---|---|---|---|
useEffect after hydration |
Hundreds of ms or more | Yes | Yes, late |
| Inline head script | Zero | Yes | ~500 bytes, early |
| SSR from cookie | Zero | No (varies per user) | No |
| CSS media query only | Zero | Yes | No, but no user override |
Switching Themes at Runtime
The ThemeController is a small client-side singleton outside React. It owns the stored preference, writes the attribute, persists the choice, and notifies the few consumers that can’t read CSS directly.
Its surface is small:
preference: the stored choice, read once at boot fromlocalStorageand validated with a type guard. Missing, invalid, or blocked storage means"system".resolved(): a pure mapping from preference plusmatchMedia("(prefers-color-scheme: dark)")to"light"or"dark".setPreference(next): writeslocalStorage(ignoring storage errors), writes a one-yearSecure; SameSite=Laxcookie, then callsapply.apply(next): sets or removesdata-themewith transitions suppressed, then notifies listeners with the resolved mode.subscribe(fn): for the few JavaScript consumers. React reads it through auseResolvedThemehook built onuseSyncExternalStore.
The controller listens to two events: the media query’s change, and the window’s storage event. It touches window at import time, so it must live in a client-only module.
Three behaviors are worth pointing out in the interview.
- The
changelistener on theMediaQueryListdoes not touch the DOM. When the preference is system, CSS has already repainted. The listener only tells canvas charts to re-read their colors. - The
storageevent fires in other tabs of the same origin when one tab writeslocalStorage. That gives you cross-tab sync for free, with noBroadcastChannel. useSyncExternalStoreis the React-safe way to read an external store without tearing. The server snapshot is a placeholder, which is fine because nothing renders markup from it.
Transitions
The tempting approach is * { transition: background-color 200ms, color 200ms } so the switch “fades”. Don’t. It makes every element on the page animate on every theme change, colors arrive out of sync because some elements have their own transitions, and it fights hover transitions all day long.
The controller does the opposite. It disables all transitions, swaps the attribute, forces a style flush by reading a computed value, and re-enables transitions two frames later. The switch is instant and crisp, and component hover transitions are untouched.
If you want a polished effect, use the View Transitions API as progressive enhancement. The browser snapshots the old page, you swap the theme, and you animate the new snapshot in with a circular clip path from the toggle.
The reveal is a thin wrapper around setPreference. If document.startViewTransition is missing or the user prefers reduced motion, it just sets the preference. Otherwise it starts a view transition whose update callback sets the preference. When the transition is ready, it animates a clip-path circle on ::view-transition-new(root), growing from the click point over about 450ms. If the browser skips the transition, the theme is already applied, so the failure is swallowed.
The token stylesheet turns off the default cross-fade on ::view-transition-old(root) and ::view-transition-new(root), so only the clip path animates. The radius is the distance from the click to the farthest viewport corner, so the circle always covers the screen. Feature-detect, respect prefers-reduced-motion, and the toggle still works everywhere.
Charts, canvas, and images
Canvas has no cascade. A chart library draws with color strings you hand it, so it must read token values from CSS and redraw on change.
type ChartVar = "--chart-series-1" | "--chart-series-2" | "--chart-grid" | "--color-text-secondary";
export type ChartPalette = Readonly<Record<ChartVar, string>>;
A small chart-theme binding owns this. It reads each chart variable with getComputedStyle on the chart’s own element, not on the document root, so nested data-theme scopes apply. It hands the palette to the chart once on mount, then again on every controller notification, and returns the unsubscribe function for cleanup.
The computed value of a custom property has its var() references substituted, so --chart-series-1: var(--blue-400) reads back as #60a5fa. One caveat: if a token is written with light-dark(), the custom property reads back as the unresolved function text, which canvas can’t parse. Keep chart tokens as plain values.
Images need a different tool depending on what they are.
- Icons and simple illustrations: inline SVG with
fill="currentColor"orvar(--color-*). They theme themselves. An SVG loaded through<img>can’t see page CSS variables. <picture>with<source media="(prefers-color-scheme: dark)">: follows only the OS. If the user overrides to light on a dark OS, the dark image still loads. Use it only when there is no override.- Decorative images: a token like
--hero-image: url(...)set per theme block. Browsers only download background images for rules that actually apply. - Photos: don’t swap them. Optionally lower brightness slightly in dark mode with a filter so they don’t glare.
Multi-brand theming
Brand is a second dimension on the same root: data-brand="acme". Each brand sheet is generated by the same build, scoped to [data-brand="acme"] and [data-brand="acme"][data-theme="dark"], and content-hashed on the CDN.
- The server maps the subdomain to a tenant and renders the brand
<link>in the head. It is render-blocking like the base tokens, so the brand is never late either. - An admin “preview brand” screen loads a different sheet at runtime: create a
<link>, wait for itsloadevent, then setdata-brand. Setting the attribute first would flash unbranded tokens. - Tenants pick one or two brand colors, not 150 tokens. The build derives hover and pressed shades and a dark-mode variant, then chooses the text color on top by contrast. Perceptual spaces like
oklch()make “same hue, lighter” predictable. - Brand input is validated as color values and compiled by your build. Tenants never upload raw CSS.
Because brand only overrides primitives and a few semantics, mode and brand compose through the cascade: 20 brands × 2 modes is 20 small sheets, not 40 full themes.
State and Data Flow
There are three places a preference can live, and they need a clear precedence.
| Store | Read by | Written when | Purpose |
|---|---|---|---|
localStorage |
Head script, controller | Every change | Device truth, works on cached HTML |
| Cookie | SSR | Every change | Correct first byte on server-rendered pages |
| Profile (server) | Controller after sign-in | Debounced PATCH | Follows the user across devices |
- First request. SSR uses the cookie if present. Otherwise no attribute, and CSS follows the OS.
- Head script. Reconciles with
localStoragebefore paint. - Controller boot. Reads the same stored value. Nothing visual changes, because the attribute is already right.
- Sign-in. Fetch the profile preference. If its server
updatedAtis newer than the one stored with the local value, adopt it withapply(). Otherwise PATCH the local value up. - User changes theme. Write
localStorageand cookie synchronously, swap the attribute, then PATCH the profile in the background. Other tabs update through thestorageevent, and other devices through a realtime message.
Use the server’s timestamp for ordering, not the client’s. Device clocks drift, and a laptop with a clock an hour fast would otherwise win every conflict. For a preference, last-writer-wins by server time is the right amount of conflict resolution.
API
// REST
GET /api/me/preferences // 200 { data: StoredPreference }
PATCH /api/me/preferences // body { theme?, contrast? } -> 200 { data: StoredPreference }
GET /brands/:brandId.:hash.css // Cache-Control: public, max-age=31536000, immutable
GET /api/brands/:brandId // brand metadata for the admin preview screen
type ThemePreference = "light" | "dark" | "system";
interface StoredPreference {
theme: ThemePreference;
contrast: "standard" | "more";
updatedAt: string; // assigned by the server
}
// Realtime: pushed on the user's existing notification socket
type ServerEvent =
| { type: "preferences.updated"; data: StoredPreference; originDeviceId: string }
| { type: "brand.updated"; brandId: string; cssUrl: string };
The device that made the change ignores its own preferences.updated by comparing originDeviceId. On brand.updated, clients load the new hashed sheet and swap the <link> after it loads. Because the URL changes with the content hash, the old sheet can stay cached forever.
Don’t open a socket just for preferences. If the app has no realtime channel, fetching preferences on focus (the visibilitychange event) is good enough. Theme changes across devices are rare.
Optimizations
| Problem | Technique | Effect |
|---|---|---|
| Flash before hydration | SSR cookie + inline head script | Correct theme on frame one |
| Re-rendering the React tree | CSS variables, attribute on <html> |
Style recalc only, zero renders |
| Expensive recalculation | Simple attribute selectors, few hundred tokens | Cheaper restyle of every element |
| Whole page fading | Transitions off during swap | Instant switch, no jank |
| Runtime CSS-in-JS churn | Static CSS, values change, rules don’t | No rule injection on switch |
| Loading all brands | One hashed sheet per tenant | ~3.6 KB instead of ~72 KB |
| Cache busting on brand edits | Content-hashed URLs, immutable cache | Repeat visits fetch nothing |
Token count is a performance knob that people forget. Every custom property defined on :root is inherited by every element. A few hundred is fine. Tens of thousands, which happens when a team generates a token for every component-state-size combination, measurably slows style recalculation. Keep component tokens on components and prune unused ones in the build.
Measure the switch in the Performance panel. You should see one “Recalculate Style” covering the document, then layout and paint. If you see scripting, something is re-rendering on theme change.
Handling Edge Cases
- Storage disabled.
localStoragethrows. The script and controller fall back to system, and the cookie still carries explicit choices for SSR. - Cookie and storage disagree. The user cleared one but not the other. SSR renders from the cookie, then the head script corrects from
localStoragebefore paint, so the device value wins. The next change rewrites both. - OS flips while the app is open. CSS handles it for system users. The
changelistener updates charts. Users with an explicit choice see nothing change, which is correct. - Printing. Nobody wants a black page on paper. Add
@media printrules that apply light tokens regardless of the attribute. - Embedded in a third-party page. An iframe widget can’t read the host’s theme. Accept a
themequery parameter or apostMessagefrom the host, validated against the allowlist. - Third-party widgets. A support chat bubble has its own CSS. Pass the resolved mode through its config API on load and on
subscribe(). - Browser chrome color.
<meta name="theme-color">accepts amediaattribute for OS-based values. When the user overrides, update itscontentfrom the controller. - Tenant picks an unreadable brand color. The build’s contrast lint fails, and the admin UI shows the ratio live while they choose.
Testing
Every theme is a full copy of your UI that can regress independently. Run visual regression on key screens for each mode, and for each brand on a smaller set. Playwright’s page.emulateMedia({ colorScheme: "dark" }) covers the system path, and setting data-theme before screenshot covers explicit overrides. Add forcedColors: "active" runs for high contrast. Contrast lint in CI catches what screenshots can’t measure.
Accessibility and Security
Accessibility
- Contrast targets. WCAG 2.x requires 4.5:1 for normal text, 3:1 for large text (24px, or about 18.7px bold), and 3:1 for UI component boundaries and meaningful graphics. Check them per mode and per brand, in the build.
- Dark mode is not inverted light mode. Pure white text on pure black causes halation for many readers. Use off-white on near-black, and lower the saturation of accent colors so they don’t vibrate.
- Forced colors. In Windows High Contrast,
@media (forced-colors: active)matches and the browser replaces your colors with system colors likeCanvas,CanvasText, andHighlight. It also removesbox-shadow, so a focus ring drawn only with a shadow disappears. Add a transparent outline, which becomes visible in that mode. Useforced-color-adjust: noneonly on things like color swatches. prefers-contrast: more. Map it to the high contrast column of semantic tokens with adata-contrastattribute, using the same pattern as mode.- The menu itself. Three options means a radio group (
role="radiogroup"or a menu withmenuitemradio), not a two-state toggle that hides “system”. Each option has a text label, not just a sun or moon icon. - Motion. The circular reveal is skipped when
prefers-reduced-motion: reducematches.
Security
- The theme cookie, query parameters, and
postMessagevalues are user input. Onlylight,dark, andsystemare ever written into HTML or attributes. - The inline script is allowed by nonce or hash, never
'unsafe-inline'. It contains no server-interpolated values except the nonce. - Tenants supply colors, not CSS. Raw tenant CSS is an injection vector: attribute selectors combined with
url()backgrounds can leak page data to another server. - The theme cookie needs no
HttpOnly(it is not secret, and the client writes it), but setSecureandSameSite=Lax.
What a Strong Answer Sounds Like
| Topic | Junior answer | Senior answer |
|---|---|---|
| Token model | A list of colors per theme | Primitive, semantic, component tiers; only semantic changes per mode |
| Mechanism | Theme object in React context | CSS variables keyed by an attribute; React never re-renders |
| First paint | Read localStorage in useEffect |
SSR cookie, plus inline blocking head script for cached HTML, with CSP nonce or hash |
| System mode | Store “dark” when the OS is dark | Store the preference; no attribute plus a media query; matchMedia only for canvas |
| Edges | Not mentioned | color-scheme, nested scopes, charts, forced colors, contrast lint, brands |
For a broader look at how a design system fits into a large codebase, see Design a Scalable Frontend Architecture.
Conclusion: How to Design a Theme Switcher
Start with the token tiers. Primitives hold raw values, semantic tokens say what a color is for and carry one alias per mode, and components only read semantic tokens. That single rule turns dark mode, high contrast, and 20 brands into extra columns of data instead of extra code.
Then make the theme a fact about the HTML, not about JavaScript. Store the preference, not the resolved mode. Let “system” be the absence of an attribute that CSS resolves on its own, render explicit choices from a cookie on the server, and close the gap on cached pages with a tiny inline script that runs before paint. If you can explain why a useEffect fix still flashes and why the head script must be inline, classic, and placed before the stylesheets, you’ve shown the interviewer you understand how browsers actually load a page.
