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

  1. System only: @media (prefers-color-scheme: dark) in CSS. No JavaScript, no flash, but no user toggle.
  2. 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.
  3. Inline script (next-themes): a small blocking script in <head> reads localStorage and sets the class before paint. next-themes does this and handles system preference, multiple themes and tab syncing. Add suppressHydrationWarning to <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 dark so form controls and scrollbars match.
  • Use the theme-color meta via generateViewport for browser UI.
  • Images: <picture> with prefers-color-scheme sources, or CSS filters for icons.
  • global-error pages render their own document and do not get your theme class.

Code example

tsx
1// app/layout.tsx
2import { ThemeProvider } from "next-themes";
3import "./globals.css";
4
5export default function RootLayout({ children }: { children: React.ReactNode }) {
6 return (
7 // next-themes sets the class before paint, so the server HTML differs
8 <html lang="en" suppressHydrationWarning>
9 <body>
10 <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
11 {children}
12 </ThemeProvider>
13 </body>
14 </html>
15 );
16}
17
18// app/components/theme-toggle.tsx
19// "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// }
25
26/* 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.

Open in study app