DEV Community

Cover image for Dark mode in Next.js 16 with no flash: Tailwind CSS 4, one inline script, no library
Nando Septian Husni
Nando Septian Husni

Posted on

Dark mode in Next.js 16 with no flash: Tailwind CSS 4, one inline script, no library

A user picks dark mode, reloads, and sees a white page for a moment before it turns dark. The server can't read localStorage, so it renders the default theme, and any code that waits for React runs after the browser has already painted that default.

This post builds a light / dark / system toggle with no theme library, then checks the first paint with Playwright. I tested everything on Next.js 16.4.6, React 19.3.0 and Tailwind CSS 4.3.3, on a production build (next build && next start) unless I say otherwise.

1. Point Tailwind's dark: variant at a class

By default, Tailwind's dark: variant follows the prefers-color-scheme media query. A manual toggle needs it to follow a class instead. The Tailwind docs do this with @custom-variant:

/* app/globals.css */
@import "tailwindcss";

@custom-variant dark (&:where(.dark, .dark *));

:root {
  --background: #ffffff;
  --foreground: #171717;
}

.dark {
  --background: #0a0a0a;
  --foreground: #ededed;
}

/* keep the template's @theme inline and body rules below this */
Enter fullscreen mode Exit fullscreen mode

Watch the rest of the file. The globals.css that create-next-app generated for me has this block:

@media (prefers-color-scheme: dark) {
  :root {
    --background: #0a0a0a;
    --foreground: #ededed;
  }
}
Enter fullscreen mode Exit fullscreen mode

If you keep it, the page background still follows the OS, while your dark: utilities follow the class. I tested a user who chose Light on a machine set to dark mode: <html> had no dark class, but the body was rgb(10, 10, 10), with light-mode cards on top. Replace the media query with the .dark selector shown above.

2. Set the class before the first paint

The fix is a small script in <head>. The browser runs it while it parses the HTML, before it parses <body> and before React loads. The Next.js guide How to prevent flash before hydration uses the same approach.

// app/theme.ts
export type Theme = "light" | "dark" | "system";

// Runs in <head> while the HTML is parsed. It ships as written, so keep it small.
export const themeScript = `(function(){try{
var t=localStorage.getItem("theme");
var d=t==="dark"||(t!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark",d);
}catch(e){}})()`;
Enter fullscreen mode Exit fullscreen mode
// app/layout.tsx
import type { Metadata } from "next";
import { themeScript } from "./theme";
import { ThemeToggle } from "./theme-toggle";
import "./globals.css";

export const metadata: Metadata = {
  title: "Dark mode test",
  description: "No-flash dark mode",
};

export default function RootLayout({ children }: LayoutProps<"/">) {
  return (
    <html
      lang="en"
      className="scheme-light dark:scheme-dark"
      suppressHydrationWarning
    >
      <head>
        <script dangerouslySetInnerHTML={{ __html: themeScript }} />
      </head>
      <body>
        <header className="flex justify-end p-4">
          <ThemeToggle />
        </header>
        {children}
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

A few details:

  • The try/catch covers browsers where localStorage is unavailable.
  • No stored value means "system", so the script falls back to matchMedia.
  • scheme-light dark:scheme-dark sets the CSS color-scheme property (Tailwind docs), so native controls like <input type="date"> and scrollbars switch too. Without it, the date picker icon stayed dark-on-dark in my test.
  • All routes still build as ○ (Static). If you store the theme in a cookie and read it with cookies() in the root layout instead, the Next.js guide notes that this opts the entire app out of static prerendering.
  • If you use a strict Content Security Policy, an inline script needs a nonce.

3. Why suppressHydrationWarning is on <html>

The script changes <html>'s class before React hydrates, so the DOM no longer matches what React rendered. I removed suppressHydrationWarning and ran next dev. The browser console showed this (trimmed):

A tree hydrated but some attributes of the server rendered HTML didn't match
the client properties. This won't be patched up. ...

  <html
    lang="en"
+   className="scheme-light dark:scheme-dark"
-   className="scheme-light dark:scheme-dark dark"
  >
Enter fullscreen mode Exit fullscreen mode

With the prop, React accepts the DOM's value for that element. React's docs say it "only works one level deep", so it hides mismatches on <html> itself, not in your page content.

4. Three approaches, one slow connection

To make a flash visible, I delayed every JS chunk under /_next/static/chunks/ by 3 seconds with Playwright, stored theme=dark and kept the OS in light mode. A requestAnimationFrame callback, added before any page script, recorded the body background at the first frame:

Approach First frame After JS loads
Inline <script> in <head> dark, rgb(10, 10, 10) dark
Set the class in a useEffect light, rgb(255, 255, 255) dark
next/script with strategy="beforeInteractive" light, rgb(255, 255, 255) dark

The useEffect result matches what the Next.js guide says: effects run after hydration, and on slow connections the browser paints the server HTML before React has loaded.

The next/script result surprised me more. With inline code, beforeInteractive didn't output a plain script tag. The HTML contained this instead:

<script>(self.__next_s=self.__next_s||[]).push([0,{"children":"(function(){try{...","id":"theme"}])</script>
Enter fullscreen mode Exit fullscreen mode

The code is queued for Next.js's client runtime, so it runs only after that JS arrives. The next/script docs also say these scripts' execution "does not block page hydration". For a theme, use a plain <script>.

5. A toggle without hydration errors

The toggle needs to show which option is active, but the server doesn't know. My first version read localStorage in a lazy useState initializer. In next dev, that logged the same hydration error, this time for aria-pressed:

+   aria-pressed={true}
-   aria-pressed="false"
Enter fullscreen mode Exit fullscreen mode

In production there was no error at all, but after hydration System still had aria-pressed="true" while the page was dark. React doesn't patch mismatched attributes, so the toggle showed the wrong state.

useSyncExternalStore handles this. React uses getServerSnapshot during server rendering and hydration (React docs), then re-renders with the real value:

// app/theme-toggle.tsx
"use client";

import { useLayoutEffect, useSyncExternalStore } from "react";
import type { Theme } from "./theme";

const query = "(prefers-color-scheme: dark)";

function readTheme(): Theme {
  try {
    const t = localStorage.getItem("theme");
    return t === "light" || t === "dark" ? t : "system";
  } catch {
    return "system";
  }
}

function applyTheme(theme: Theme) {
  const dark =
    theme === "dark" || (theme === "system" && matchMedia(query).matches);
  document.documentElement.classList.toggle("dark", dark);
}

function subscribe(onChange: () => void) {
  const sync = () => {
    applyTheme(readTheme());
    onChange();
  };
  const mq = matchMedia(query);
  mq.addEventListener("change", sync);
  window.addEventListener("storage", sync); // other tabs
  window.addEventListener("themechange", sync); // this tab
  return () => {
    mq.removeEventListener("change", sync);
    window.removeEventListener("storage", sync);
    window.removeEventListener("themechange", sync);
  };
}

function setTheme(theme: Theme) {
  try {
    if (theme === "system") localStorage.removeItem("theme");
    else localStorage.setItem("theme", theme);
  } catch {}
  window.dispatchEvent(new Event("themechange"));
}

const options: Theme[] = ["light", "dark", "system"];

export function ThemeToggle() {
  // null on the server and during hydration, the real value right after.
  const theme = useSyncExternalStore(subscribe, readTheme, () => null);

  // From the Next.js guide: re-apply after Strict Mode's dev remount.
  useLayoutEffect(() => applyTheme(readTheme()), []);

  return (
    <div role="group" aria-label="Color theme" className="flex gap-1">
      {options.map((option) => (
        <button
          key={option}
          type="button"
          aria-pressed={theme === option}
          onClick={() => setTheme(option)}
          className="rounded px-3 py-1 text-sm capitalize ring-1 ring-zinc-300 aria-pressed:bg-zinc-900 aria-pressed:text-white dark:ring-zinc-700 dark:aria-pressed:bg-zinc-100 dark:aria-pressed:text-zinc-900"
        >
          {option}
        </button>
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

How the pieces fit:

  • This tab: setTheme writes localStorage and fires a custom themechange event. The storage event doesn't fire in the window that made the change, so the custom event is needed.
  • Other tabs: the storage event updates them.
  • System: the matchMedia listener updates the page when the OS setting changes.
  • Put the toggle in the root layout. I first had it only on the home page, and a second tab open on /about didn't update, because nothing there was listening.
  • The useLayoutEffect: the Next.js guide says React Strict Mode's remount in development can reset attributes on <html>, and suggests re-applying the theme. I couldn't trigger that reset on 16.4.6 (the class survived reloads, edits to the page and layout, and client navigation in next dev), but it's one line, so I kept it.

6. What the Playwright run checked

On the production build, with no console errors:

  • Stored dark + 3-second JS delay: dark at the first frame.
  • OS dark, nothing stored: dark, with color-scheme: dark.
  • Stored light, OS dark: light, and the body is white.
  • Click Dark: aria-pressed="true" on Dark, localStorage.theme === "dark", and a second tab switched too.
  • Reload: still dark, Dark still pressed.
  • Click System: the key is removed. Switching the emulated OS to dark then turned the page dark.
  • Client-side navigation to /about: the class stays.

Wrap-up

  1. Override dark: with @custom-variant dark (&:where(.dark, .dark *));.
  2. Delete the template's prefers-color-scheme block, or it fights your toggle.
  3. Set the class with a plain inline <script> in <head>. Not useEffect, not next/script.
  4. Add suppressHydrationWarning to <html> only.
  5. Read the stored theme in the toggle with useSyncExternalStore and a null server snapshot.
  6. Add scheme-light dark:scheme-dark so native controls match.

Does your toggle offer a System option, or only light and dark?

I keep launch checks like these as free, MIT-licensed agent skills for Claude Code, Cursor and Codex: npx skills add nandot12/nextjs-launch-skills · GitHub

Top comments (0)