Next.jsMedium
How do you handle dark mode in Next.js?
Define light and dark tokens as CSS variables, switch them with a class or data-theme attribute on <html>, respect prefers-color-scheme as the default, and persist the user's choice. The hard part is avoiding a flash of the wrong theme before hydration, solved with a cookie read on the server or a tiny inline script.
Approaches
- System only:
@media (prefers-color-scheme: dark)in CSS. No JavaScript, no flash, but no user toggle. - Cookie-based (server-aware): store the choice in a cookie, read it in the root layout with
cookies(), and render<html className="dark">. No flash, but reading cookies in the root layout makes it request-time; with Cache Components, it is often better to keep the layout static and use approach 3. - Inline script (
next-themes): a small blocking script in<head>readslocalStorageand sets the class before paint.next-themesdoes this and handles system preference, multiple themes and tab syncing. AddsuppressHydrationWarningto<html>because the class differs from the server HTML.
Tailwind v4
@custom-variant dark (&:where(.dark, .dark *)); makes dark: utilities follow the class instead of the media query.
Details
- Set
color-scheme: light darkso form controls and scrollbars match. - Use the
theme-colormeta viagenerateViewportfor browser UI. - Images:
<picture>withprefers-color-schemesources, or CSS filters for icons. global-errorpages render their own document and do not get your theme class.
Code example
tsx
1// app/layout.tsx2import { ThemeProvider } from "next-themes";3import "./globals.css";45export default function RootLayout({ children }: { children: React.ReactNode }) {6 return (7 // next-themes sets the class before paint, so the server HTML differs8 <html lang="en" suppressHydrationWarning>9 <body>10 <ThemeProvider attribute="class" defaultTheme="system" enableSystem>11 {children}12 </ThemeProvider>13 </body>14 </html>15 );16}1718// app/components/theme-toggle.tsx19// "use client";20// import { useTheme } from "next-themes";21// export function ThemeToggle() {22// const { resolvedTheme, setTheme } = useTheme();23// return <button onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}>Toggle theme</button>;24// }2526/* app/globals.css */27// @import "tailwindcss";28// @custom-variant dark (&:where(.dark, .dark *));29// :root { color-scheme: light; } .dark { color-scheme: dark; }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.