All articles
Web DevelopmentNovember 16, 2026 6 min read

Why Our Design System's Tokens Broke Dark Mode in Server Components

We shipped a design system with CSS variables, theme toggles, and server components. Then half our pages flashed white on reload and the other half rendered the wrong theme entirely. Here's what we learned.

A client asked us to add dark mode to an App Router app with a mature design token system. It should have been a two-day job. It took eleven, and three of those days were spent arguing about whether CSS variables even work with server components. They do — but not the way most tutorials assume.

This is the breakdown of what went wrong, why the usual next-themes pattern falls apart when your tokens live in TypeScript, and the architecture we ended up with.

The Setup That Looked Reasonable

The app was Next.js 15, App Router, React 19. Design tokens lived in a shared package, authored in TypeScript so product teams could import them into Tailwind config, Storybook, and the occasional inline style.

// packages/tokens/src/colors.ts
export const colors = {
  surface: {
    light: '#fdfcf8',
    dark: '#0f1115',
  },
  text: {
    light: '#111318',
    dark: '#e8e6df',
  },
} as const;

We emitted these as CSS custom properties at build time:

:root {
  --surface: #fdfcf8;
  --text: #111318;
}

[data-theme='dark'] {
  --surface: #0f1115;
  --text: #e8e6df;
}

A <ThemeProvider> client component read localStorage, set data-theme on <html>, and everything downstream used var(--surface). Textbook stuff.

Then we shipped it to staging and three things happened at once.

Symptom 1: The Flash

Users with dark mode set saw a full white flash on every navigation. Classic FOUC, except this was App Router, so the usual next-themes blocking script wasn't firing before the server-rendered HTML painted.

Symptom 2: Server Components Rendered the Wrong Theme

We had a server component that rendered a chart with inline SVG fills pulled from the token module:

// app/dashboard/Chart.tsx (server component)
import { colors } from '@acme/tokens';

export function Chart({ data }: { data: Series[] }) {
  return (
    <svg>
      {data.map((d) => (
        <rect key={d.id} fill={colors.surface.light} />
      ))}
    </svg>
  );
}

The server has no idea what theme the user is on. It picked light because that was the default. Dark-mode users got light charts embedded in a dark page.

Symptom 3: Hydration Mismatches

The data-theme attribute, set by the client provider, didn't match what the server rendered. React 19 is more vocal about this than React 18. We got a sea of console errors and, worse, a few components that failed to hydrate interactive handlers at all.

Why the Standard Advice Doesn't Work Here

Most dark-mode guides assume two things: your tokens are pure CSS, and your theme-sensitive rendering happens client-side. Neither was true for us.

When tokens are TypeScript values, any server component importing them bakes a specific theme into the HTML. There's no var() indirection to save you at paint time. And when half your tree is RSC, you can't just wrap everything in a client provider and call it done — you'd lose the entire point of server components.

The real fix has three parts: get the theme on the server before render, make tokens CSS-first with TypeScript as a secondary consumer, and stop pretending localStorage is a source of truth.

Part 1: Theme on the Server

The browser can't tell the server what theme to render. A cookie can. We added a small server action that writes a theme cookie, and a root layout that reads it:

// app/layout.tsx
import { cookies, headers } from 'next/headers';

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const cookieStore = await cookies();
  const stored = cookieStore.get('theme')?.value;

  const headerList = await headers();
  const hint = headerList.get('sec-ch-prefers-color-scheme');

  const theme = stored ?? hint ?? 'light';

  return (
    <html lang="en" data-theme={theme} suppressHydrationWarning>
      <body>{children}</body>
    </html>
  );
}

Two details worth calling out. First, sec-ch-prefers-color-scheme is a client hint — you have to opt in via Accept-CH response headers, but once you do, Chromium browsers send the user's OS preference on the first request. No flash, no JavaScript needed. Safari and Firefox don't send it yet, so we fall back to light for first-time visitors and let the client correct on next paint.

Second, suppressHydrationWarning on <html> is there because the client provider may still swap the attribute after mount. That's fine — the mismatch is intentional and scoped to one attribute.

The Cookie Write

// app/actions/theme.ts
'use server';

import { cookies } from 'next/headers';

export async function setTheme(theme: 'light' | 'dark' | 'system') {
  const cookieStore = await cookies();
  cookieStore.set('theme', theme, {
    path: '/',
    maxAge: 60 * 60 * 24 * 365,
    sameSite: 'lax',
  });
}

The toggle button calls this action and then router.refresh() so the server re-renders with the new theme. No flash because the next paint already has the correct data-theme.

Part 2: CSS-First Tokens

We inverted the token pipeline. CSS variables became the source of truth; TypeScript became a derived artifact.

// packages/tokens/src/index.ts
export const token = {
  surface: 'var(--surface)',
  text: 'var(--text)',
  accent: 'var(--accent)',
} as const;

export type Token = typeof token;

Now when a server component references token.surface, it emits the CSS variable reference, not a literal hex. The browser resolves it against whatever data-theme is on the ancestor. One HTML payload, both themes, zero mismatch.

The Chart component becomes:

import { token } from '@acme/tokens';

export function Chart({ data }: { data: Series[] }) {
  return (
    <svg>
      {data.map((d) => (
        <rect key={d.id} fill={token.surface} />
      ))}
    </svg>
  );
}

For the rare case where you genuinely need the resolved color on the server — say, generating an Open Graph image — we expose a resolveToken(name, theme) helper that reads the raw hex map. It's an escape hatch, not the default.

What About Tailwind?

Tailwind's config points at the same CSS variables:

// tailwind.config.ts
export default {
  theme: {
    colors: {
      surface: 'var(--surface)',
      text: 'var(--text)',
      accent: 'var(--accent)',
    },
  },
};

This means bg-surface works identically in both themes with no dark: variants scattered across components. That alone deleted about 400 lines of utility classes.

Part 3: Respect the System Preference Without Lying

The third mode — system — is where most implementations get sloppy. If a user picks "follow system," you can't bake that into a cookie as dark or light, because their OS preference might change. We store the literal string system and resolve it twice: once optimistically on the server using the client hint, and once authoritatively on the client via matchMedia.

'use client';

import { useEffect } from 'react';

export function SystemThemeSync({ mode }: { mode: string }) {
  useEffect(() => {
    if (mode !== 'system') return;
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const apply = () => {
      document.documentElement.dataset.theme = mq.matches ? 'dark' : 'light';
    };
    apply();
    mq.addEventListener('change', apply);
    return () => mq.removeEventListener('change', apply);
  }, [mode]);

  return null;
}

This component is tiny, runs once, and handles the edge case of users changing their OS theme mid-session without a reload.

The Accessibility Bit Nobody Mentions

Dark mode interacts with reduced motion, high contrast, and forced colors in ways that will embarrass you in an audit. Two things we added after a WCAG review:

  • A @media (forced-colors: active) block that remaps our tokens to CanvasText, Canvas, and LinkText so Windows High Contrast users see something sensible.
  • A minimum contrast check in CI. We run every token pair through a contrast function and fail the build if any pairing drops below 4.5:1 for body text. It caught two regressions in the first week.

If you're building a design system seriously, this stuff isn't optional. We write more about these patterns in our design system engagements.

What We'd Do Differently

If we were starting over on a new project tomorrow, we'd make three decisions on day one. Author tokens as CSS variables first and generate the TypeScript references from them — not the other way around. Put the theme in a cookie and read it in the root layout before anything else renders. Treat system as a first-class value, not a client-only afterthought.

The tempting shortcut is to slap next-themes on the root and move on. It works until a server component needs to know what color something is, and then you're unpicking it for a week. Start with the server knowing, and everything downstream gets easier.

#Next.js#Design Systems#React Server Components#CSS#Accessibility

Want a team like ours?

72Technologies builds production software for the kind of teams who actually read this blog.

Start a project