nextjs dark mode with tailwind css example

In this section we will see how to use dark mode in nextjs with tailwind css using next-themes library. next-themes is perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing.

Tool Use


Tailwind CSS 3.v


First you need to setup NextJS project with tailwind css. You can install manually or you read below blog.

Install Tailwind CSS In Next JS with Typescript

How to Install & Setup Tailwind CSS v3 In NextJS

Install next-themes for dark mode

Run below command to install next-themes.

npm install next-themes
# or
yarn add next-themes

Add dark mode class in tailwind.config.js


module.exports = {
  darkMode: 'class',
  content: [
  theme: {
    extend: {},
  plugins: [],

Now, you need to import them in pages/_app.tsx or _app.js.

pages/_app.tsx or _app.js

import { ThemeProvider } from 'next-themes'

function MyApp({ Component, pageProps }) {
 return (
  <ThemeProvider attribute='class'>
   <Component {...pageProps} />

export default MyApp

Now import useTheme and use dark mode toggle switch.

pages/index.js or pages/index.tsx

import Head from "next/head";
import React from "react";
import { useTheme } from 'next-themes'

export default function Home() {
  const { theme, setTheme } = useTheme()
  return (
        <title>Next App Dark Mode With Tailwind CSS</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      <div className="flex flex-col items-center justify-center h-screen bg-white dark:bg-black">
          onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
          className="px-4 py-2 text-white bg-black rounded dark:bg-white dark:text-black">
          Dark Toggle
        <div className="mt-6">
            className="max-w-sm p-6 bg-white border border-gray-200 rounded-lg shadow-md hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700"
            <h5 className="mb-2 text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
              NextJS dark Mode With Tailwind CSS
            <p className="font-normal text-gray-700 dark:text-gray-400">
              install & setup nextjs dark mode using tailwind css 3

Nextjs before dark mode toggle button.

nextjs light mode toggle switch with tailwind css

After click dark mode toggle button.

nextjs dark mode toggle switch with tailwind css

Run server

npm run dev

Read Also

Create Responsive Navbar Menu in Next js with Tailwind CSS