Guides/Web Development
Web Development7 min read

How to Implement Dark Mode in Next.js with Tailwind CSS

Add dark mode to your Next.js app — support system preferences, allow manual toggle, persist the choice, and avoid the flash of incorrect theme on page load.

Configure Tailwind for Dark Mode

In tailwind.config.ts, set darkMode: "class". This enables dark mode via a class on the <html> element rather than relying solely on the system preference media query. Add dark: variants to any element: className="bg-white dark:bg-gray-900 text-gray-900 dark:text-white". Tailwind generates the dark: utilities automatically — no extra CSS needed.

Install next-themes

next-themes handles everything: initial theme detection, persistence, and flash prevention. Install: npm install next-themes. Wrap your layout: import { ThemeProvider } from "next-themes"; export default function RootLayout({ children }) { return (<html suppressHydrationWarning><body><ThemeProvider attribute="class" defaultTheme="system" enableSystem>{children}</ThemeProvider></body></html>) }. suppressHydrationWarning prevents React warnings caused by the theme class being added before hydration.

Add a Theme Toggle Button

In any client component: import { useTheme } from "next-themes"; function ThemeToggle() { const { theme, setTheme } = useTheme(); return (<button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>Toggle</button>) }. next-themes automatically persists the choice to localStorage and applies the correct class on subsequent page loads. The toggle works across all tabs instantly.

Prevent Flash of Wrong Theme

The suppressHydrationWarning on <html> and next-themes' built-in script injection together prevent the flash of incorrect theme (FOIT/FOUC). next-themes injects a tiny inline script before the page renders that reads localStorage and applies the correct class before the browser paints. Without this, users with dark mode set would briefly see the light theme on every page load.

Handle System Preference Changes

With defaultTheme: "system" and enableSystem, next-themes listens to the prefers-color-scheme media query and switches automatically when the system changes. This means users who set their OS to auto dark mode (light during day, dark at night) get the correct theme without any manual action. Their explicit override (if they toggled manually) takes precedence over the system preference.

Need Help?

Want this done for you?

Our engineering team handles implementations like this every week. Get a free scoping call — we will tell you exactly what it takes and what it costs.

Book a free call

© 2026 NexWorldTech — Built for Global Dominance.