← All writing

Frontend· December 10, 2024 · 9 min

Building a Zero-FOUC Dark Mode with CSS Variables and Next.js

A deep dive into creating seamless multi-theme switching that works on first paint, with no flash of unstyled content, using CSS custom properties and the Next.js App Router.

The Problem

Flash of unstyled content (FOUC) happens when a page renders before your theme styles are applied. With dark mode, this means users see a bright white flash before the dark theme kicks in — jarring and unprofessional.

The Solution: CSS Custom Properties

By storing theme values as CSS custom properties on :root, we can switch themes with a single class change on the html element.

:root {
  --bg: #ffffff;
  --text: #000000;
}

:root.dark {
  --bg: #0a0a0a;
  --text: #ffffff;
}

Preventing the Flash

The trick is running a tiny inline script in the <head> — before any rendering — that reads the user's saved preference and sets the class synchronously.

<script>
  const theme = localStorage.getItem('theme') || 'dark'
  document.documentElement.classList.add(theme)
</script>

Because this runs before the browser paints, there is no flash.

Next.js App Router Setup

In the App Router, place this in your root layout.tsx inside the <head> using dangerouslySetInnerHTML:

<script
  dangerouslySetInnerHTML={{
    __html: `(function(){var t=localStorage.getItem('theme')||'dark';document.documentElement.classList.add(t)})()`,
  }}
/>

The IIFE ensures it runs immediately and does not leak variables into global scope.

Wrapping Up

This pattern works for any number of themes, not just light/dark. Store the theme name in localStorage, set it on :root before paint, and drive all your styles through CSS custom properties.