Fixing Dark Mode Flash in Next.js: Simple & Bulletproof
Why dark mode flash happens in SSR apps and the simple inline script pattern that fixes it forever.
Few things feel less professional on a developer portfolio than opening a website late at night and having a blinding white flash hit your eyes for 200ms before dark mode kicks in.
This happens because the HTML from the server renders before the client's JavaScript has read the user's preference from localStorage.
Here is the exact approach I use to guarantee zero-flash theme persistence in Next.js.
The solution is to inspect the theme before the browser paints the body. By placing an inline, non-deferred script inside the <head> of the document, the script runs synchronously:
In modern Next.js using next-themes, this is handled cleanly with <ThemeProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange>.
Pair this with suppressHydrationWarning on your <html> element, and your dark mode will load instantly with zero flicker on any connection.