Dark mode on this blog has always had a tiny cheat in it. Before React loads, a little inline script reads your saved theme from localStorage and paints the page dark. It works, but it always felt like a hack. The server renders the page without knowing your theme, and a script patches it up in the browser.
The "proper" fix seemed obvious. Store the theme in a cookie, read it on the server, render the right class from the start. One line in the root layout:
// app/layout.tsx import { cookies } from " next/headers " ;
export default async function RootLayout ({ children }) { const theme = ( await cookies ()). get ( " theme " )?. value ;
return ( < html lang = "en" className = { theme === " dark " ? " dark " : undefined } > { /* ... */ } </ html > ); }
Enter fullscreen mode
Exit fullscreen mode
I tried it on a copy of this blog. Dark mode worked on the very first byte. No script, no patching.β¦