Skip to main content
Dark Mode Without the Flash in Next.js 16: How We Ship a Blocking Theme Script, color-scheme, and a Hydration-Safe Toggle

Dark Mode Without the Flash in Next.js 16: How We Ship a Blocking Theme Script, color-scheme, and a Hydration-Safe Toggle

November 14, 2026
Frontend Engineering
7 min read

Headline: Dark mode flashes in the Next.js App Router because the server renders HTML before it can read a theme saved in localStorage, and a useEffect applies that theme only after the first paint. A small inline script in the root layout's head element that sets the html class and color-scheme before the body is parsed removes the flash and keeps every page static.

Key takeaways

The flash is a timing problem: the server cannot read localStorage, so the first paint uses the default theme until client JavaScript corrects it.

An inline blocking script in the head element fixes it, because the browser runs the script before it parses the body, so the first paint already has the right class.

Reading a theme cookie with cookies() in the root layout also prevents the flash, but it makes every route render per request.

The CSS color-scheme property, not the dark class, is what switches native scrollbars, form controls and the light-dark() function.

A theme toggle should take its icon from CSS and its state from useSyncExternalStore, so server and client markup match during hydration.

Why does dark mode flash on page load in Next.js?

Dark mode flashes in Next.js because the theme preference lives in the browser while the HTML is rendered without it. A statically rendered page is built once, with no access to a visitor's localStorage. The browser paints that HTML immediately; React hydrates afterwards, and only then does a useEffect read the saved theme and add the dark class. Every frame between the first paint and that effect uses the default theme.

Moving the logic into useLayoutEffect does not help, because hydration itself starts after the server HTML has been painted. In the projects we build at Devya, the fix has to run while the browser parses the HTML, before React is on the page.

For mostly static sites, our team stores the theme in localStorage and applies it with an inline script. A cookie lets the server render the correct theme, but reading it in the root layout opts every route out of static rendering. These are the options we compared:

Inline script plus localStorage: no flash, pages stay static, the server does not know the theme, and the cost is a few hundred bytes of render-blocking inline JavaScript.

Cookie read with cookies() in the root layout: no flash and the server knows the theme, but every route renders per request and the HTML loses CDN caching.

useEffect in a client provider: pages stay static, but the flash remains.

CSS prefers-color-scheme only: no flash and no JavaScript, but there is no user toggle; the operating system decides.

The cookie route has one more catch in Next.js 16. With cacheComponents enabled, cookies() is runtime data that Next.js expects inside a Suspense boundary, and no boundary can wrap the html element whose class the cookie would set. The next-themes library uses the inline-script approach internally, so the first option's trade-offs apply to it as well.

How do we write a blocking theme script in the App Router?

A blocking theme script is a self-contained function rendered as an inline script tag in the root layout's head element; the browser runs it before it parses the body. Ours reads the saved value with localStorage.getItem('theme'), accepts only 'light' or 'dark', calls document.documentElement.classList.toggle('dark', ...), sets document.documentElement.style.colorScheme, and catches errors, because localStorage throws when storage is disabled.

The html element needs suppressHydrationWarning, because the script changes its class and style before React hydrates. React's suppressHydrationWarning only works one level deep, so it does not hide real mismatches elsewhere in the tree.

We render the script from the Server Component root layout with dangerouslySetInnerHTML, not from a client provider, so it ships as plain HTML and needs no client bundle. The fallback when nothing is saved is a product decision: we ship exactly two options, Light and Dark, and fall back to the design's default theme. A product that should follow the operating system can read matchMedia('(prefers-color-scheme: dark)').matches in the same script.

Sites with a Content Security Policy must allow the inline script. A nonce-based CSP forces dynamic rendering in Next.js, so we allow the constant script with a sha256 hash in script-src and regenerate the hash whenever the script text changes.

How do we switch themes without every color animating?

Elements with CSS transitions on color or background-color animate at different speeds when the theme class flips, so the page appears to repaint in stripes. Our setTheme function injects a style element that sets transition: none on every element, flips the dark class and color-scheme, saves the choice to localStorage inside a try/catch, forces a style recalculation by reading getComputedStyle(document.body).opacity, and removes the style element in a setTimeout one millisecond later.

The next-themes option disableTransitionOnChange uses the same technique, so teams already on that library can switch it on instead of writing their own.

How do we render the toggle without a hydration mismatch?

A toggle that chooses a sun or moon icon from a theme value causes a hydration mismatch, because the server always renders the default theme. We render both icons and let CSS show one, using Tailwind classes such as dark:hidden and hidden dark:block, so server and client markup are identical.

The state the button needs, such as aria-pressed, comes from useSyncExternalStore, the React hook that subscribes a component to an external store and accepts a separate server snapshot. Our store is the html element's class list, observed with a MutationObserver. During hydration React uses the server snapshot, null, then re-renders with the real value, so there is no mismatch and every toggle on the page reads the same source of truth.

Other tabs stay in sync through the storage event, which fires in every same-origin tab except the one that wrote the value. Writing an unchanged value fires no event, so two tabs cannot loop.

How do Tailwind CSS v4 and light-dark() fit in?

Tailwind CSS v4's dark variant follows prefers-color-scheme by default. A class-based toggle needs one line in the main stylesheet, @custom-variant dark (&:where(.dark, .dark *)); which points the variant at the dark class.

The CSS light-dark() function returns its first color when the element's used color scheme is light and its second when it is dark. It has been Baseline since 2024 and only switches when color-scheme is set, which is why our script sets colorScheme as well as the class. Setting color-scheme also turns scrollbars, select menus and date pickers dark.

FAQ

Q: Does suppressHydrationWarning hide other hydration errors?

A: No. React's suppressHydrationWarning only silences mismatches in the attributes and text of the element it is set on, one level deep, so mismatches anywhere below the html element still surface.

Q: Do we still need next-themes in Next.js 16?

A: No, it is optional. next-themes wraps the same inline-script approach in a provider and a useTheme hook; a hand-written version is a few dozen lines and avoids a client provider around the whole app.

Q: Can the dark mode flash be prevented without JavaScript?

A: Only when the theme follows the operating system. CSS with prefers-color-scheme or light-dark() needs no script, but a saved user choice must be applied by an inline script or by server-rendered markup from a cookie.

Q: Does an inline theme script slow down the page?

A: It blocks HTML parsing only while it reads one localStorage key and sets two properties on the html element, and it adds no network request, unlike an external script file.

Q: How do we make the mobile browser toolbar match the chosen theme?

A: The theme-color meta tag sets the toolbar color. The Next.js viewport export accepts themeColor entries with a prefers-color-scheme media query, but a saved choice that differs from the operating system needs setTheme to update the theme-color tag as well.