How to Set Up and Customize Light and Dark Mode in shadcn with Next.js

If you've created a Next.js project with shadcn/ui recently, there's a good chance dark mode is already set up.
I noticed this while looking through a fresh project. I opened app/globals.css expecting to add the theme colors, but the light and dark values were already there. Then I checked the components folder and found a theme-provider.tsx file that had already been created for me.
That raised a more useful question: if shadcn has already done most of the setup, what do you actually need to build?
In this guide, we'll look at the dark-mode setup that comes with a generated shadcn project, understand how the pieces work together, and build a theme switcher that users can control. We'll also look at how to customize the colors without adding light and dark classes to every component.
By the end, you'll know:
- Where shadcn stores its light and dark theme values
- How CSS variables and Tailwind theme variables work together
- What
next-themesdoes in a Next.js project - How to add a two-state or three-option theme switcher
- How to add your own theme tokens
We'll start with the generated project and work through the theme setup before building the switcher.
Before you start: This guide follows the Next.js project generated by shadcn/create. Your project may look a little different if you use another framework, an older shadcn setup, or a different component style. I'll point out the parts you should check in your own project.
The examples and screenshots in this article are based on the companion project. Once you have the project locally, you can run pnpm install and pnpm dev to try it yourself.
The same page is shown in both themes. Only the active theme values change.
The page uses the same JSX in both screenshots. The theme changes the values behind the CSS variables, and the browser updates the styles.
Table of Contents
- Project Setup and Versions
- 1. Create a shadcn Project
- 2. What shadcn Has Already Configured
- 3. Where the Theme Colors Live
- 4. How Tailwind Gets its Theme Classes
- 5. What next-themes Does
- 6. The Theme Provider That's Already in Your Project
- 7. Build a Theme Switcher
- 8. Why the Icon Animation May Not Work
- 9. Customize Your Theme
- Conclusion
- References
Project Setup and Versions
The versions below are the versions used in the companion project, which was generated in August 2026. Shadcn's generated output changes over time, so check your own package.json if you're following along with a newer project.
| Package | Version |
|---|---|
next | 16.2.6 |
react | 19.2.4 |
next-themes | 0.4.6 |
@base-ui/react | 1.7.0 |
tailwindcss | 4 |
The project's components.json includes "style": "base-nova" and "baseColor": "stone". The base-nova style uses Base UI primitives. This matters when we build the dropdown switcher later, because the Base UI version uses the render prop where many older Radix-based examples use asChild.
1. Create a shadcn Project
You don't need to configure Next.js and Tailwind from scratch for this guide. Shadcn's project builder can generate a starter project with the theme setup included.
Open shadcn/create and select Get Started.
Choose the style, base color, chart color, fonts, icon library, and radius from the controls. These choices affect the theme values that will be added to your project. We'll look at those values in the next section.
When you're happy with the setup, select Get Code, choose Next.js, and copy the command.
Run the command in your terminal. The preset ID in your command may be different from the example below:
pnpm dlx shadcn@latest init --preset b0 --template next If you're building a complete product, you may prefer to start with a ready-made shadcn template and adapt it to your app. The same theme setup covered in this guide can be used in a template-based project.
The generated project has a structure similar to this:
shadcn-light-dark-theme/ ├── app/ │ ├── globals.css # every theme token, light and dark │ ├── layout.tsx # fonts and ThemeProvider already wired │ └── page.tsx ├── components/ │ ├── theme-provider.tsx # next-themes, already configured │ └── ui/button.tsx ├── lib/utils.ts └── components.json Start the development server:
pnpm dev Open http://localhost:3000. The companion project also includes a keyboard shortcut: pressing d switches between light and dark mode.
The important point is that the theme setup is already present. Before adding anything, let's see what the generator has configured.
2. What shadcn Has Already Configured
A generated project includes most of the pieces you need for light and dark themes. Here's where to find them:
| Part | Where to find it | Included |
|---|---|---|
| Light theme values | app/globals.css then :root | Yes |
| Dark theme values | app/globals.css then .dark | Yes |
Tailwind's dark: variant | app/globals.css then @custom-variant | Yes |
| Tailwind utilities for theme tokens | app/globals.css then @theme inline | Yes |
next-themes package | package.json | Yes |
| Theme provider | components/theme-provider.tsx | Yes |
| Provider added to the app | app/layout.tsx | Yes |
| Hydration warning handling | app/layout.tsx | Yes |
| A visible theme switcher | Your UI | You add this |
So the main piece you'll usually need to add is the control that lets someone choose a theme. The rest is already configured, although it's worth understanding before you start customizing it.
3. Where the Theme Colors Live
Open app/globals.css. You'll find two groups of CSS variables: one inside :root and another inside .dark.
Here's a shortened example based on the generated project:
:root { --background: oklch(1 0 0); --foreground: oklch(0.147 0.004 49.25); --card: oklch(1 0 0); --card-foreground: oklch(0.147 0.004 49.25); --primary: oklch(0.555 0.163 48.998); --primary-foreground: oklch(0.987 0.022 95.277); --muted: oklch(0.97 0.001 106.424); --muted-foreground: oklch(0.553 0.013 58.071); --border: oklch(0.923 0.003 48.717); --radius: 0.625rem; /* …about thirty in total */ } .dark { --background: oklch(0.147 0.004 49.25); --foreground: oklch(0.985 0.001 106.423); --card: oklch(0.216 0.006 56.043); --card-foreground: oklch(0.985 0.001 106.423); --primary: oklch(0.473 0.137 46.201); --primary-foreground: oklch(0.987 0.022 95.277); --muted: oklch(0.268 0.007 34.298); --muted-foreground: oklch(0.709 0.01 56.259); --border: oklch(1 0 0 / 10%); } The idea is straightforward:
:root → light theme values .dark → dark theme values Both blocks use the same variable names. The values change depending on whether the dark class is present on the page.
For example, --background is white in the light theme and near-black in the dark theme. --foreground changes in the opposite direction so the text remains visible against the background.
You'll also see variables such as --radius. It isn't a color, but it's part of the theme configuration. In this setup, the radius is defined once because the corner shape doesn't need a separate value for dark mode.
Why Semantic Tokens Are Useful
Theme variables are especially useful when you're building components. Compare these two examples.
Without semantic tokens, you might add separate light and dark colors directly to the component:
<div className="bg-white text-black dark:bg-black dark:text-white"> Hello </div> That works, but you have to repeat the same decisions throughout your app. If your color palette changes, you'll need to find and update all those classes.
With semantic tokens, the component can use the theme variable instead:
<div className="bg-background text-foreground"> Hello </div> The component doesn't need to know whether the page is in light or dark mode. It uses background and foreground, and the active theme supplies the right values.
This is also why shadcn components such as Card can adapt without needing dark-mode classes of their own:
<Card> <CardHeader> <CardTitle>Hello</CardTitle> </CardHeader> </Card> If you open components/ui/card.tsx, you'll see classes such as bg-card and text-card-foreground. The component uses the semantic tokens, while the theme defines what those tokens look like.
The same idea applies when you add more UI to the project. If you need examples of individual elements built for the shadcn ecosystem, you can refer to Shadcn Components and adapt the ones that fit your interface. Keep the semantic tokens in place so those components follow your light and dark themes.
Understanding the Foreground Pairs
Many theme tokens come in pairs. The first token describes a surface, and the -foreground token describes the text or content that appears on top of it.
| Surface token | Foreground token |
|---|---|
--background | --foreground |
--card | --card-foreground |
--primary | --primary-foreground |
--muted | --muted-foreground |
For example, bg-primary text-primary-foreground uses a matching background and text color. The theme defines both values together so the combination works across its light and dark palettes.
Some tokens, such as --border, --input, and --ring, don't need a foreground pair because they're used for borders, input outlines, and focus indicators.
The companion project displays the token pairs as simple tiles. Each tile uses the same bg-<name> text-<name>-foreground pattern.
The markup stays the same in both screenshots. Only the active CSS variable values change. The demo also includes a custom --warning token to show how you can extend the theme.
4. How Tailwind Gets its Theme Classes
There's one more part of globals.css that's easy to overlook: the @theme inline block.
A CSS variable such as --primary is available to CSS, but defining it doesn't automatically create Tailwind classes such as bg-primary or text-primary. Tailwind needs to know which variables should become utility classes.
That's what this block does:
@theme inline { --color-background: var(--background); --color-foreground: var(--foreground); --color-primary: var(--primary); --color-primary-foreground: var(--primary-foreground); --color-muted: var(--muted); /* …one line per token */ --radius-sm: calc(var(--radius) * 0.6); --radius-md: calc(var(--radius) * 0.8); --radius-lg: var(--radius); --radius-xl: calc(var(--radius) * 1.4); } For example, this line:
--color-primary: var(--primary); connects the CSS variable --primary to Tailwind's color utilities. It allows you to use classes such as bg-primary, text-primary, and border-primary.
This is an important step when you add your own tokens. If you define --brand in :root but don't add a matching --color-brand entry in @theme inline, Tailwind won't generate the bg-brand utility for you. The CSS variable can exist and still not be available as a Tailwind utility.
The inline keyword is also important here. It allows the generated utilities to reference the underlying CSS variable, so they use the current value when the theme changes.
What the dark: Variant Does
You'll also find this line in globals.css:
@custom-variant dark (&:is(.dark *)); This defines how Tailwind's dark: variant works in this setup. A class such as dark:hidden applies when the element is inside an ancestor with the dark class.
There are two details to remember:
- The theme is represented by a
darkclass, rather than adata-themeattribute. - The selector targets descendants of the element with the
darkclass.
In this project, next-themes adds the class to the <html> element. That means the elements inside the page can use dark: utilities as expected.
Here's the relationship between the theme class, CSS variables, and Tailwind utilities:
.dark on <html> ↓ --primary changes value (globals.css) ↓ --color-primary reads it (@theme inline) ↓ bg-primary compiles to var(--primary) ↓ every element using bg-primary repaints When the theme changes, the browser updates the CSS variables and recalculates the styles that use them. Your components don't need to re-render just because a theme color changed.
So far, we've looked at the CSS side. The next question is what adds or removes the dark class.
5. What next-themes Does
CSS defines what the light and dark themes look like. It doesn't remember a visitor's choice or decide which theme should be active. That's handled by JavaScript.
The generated Next.js project uses next-themes for this.
The library handles a few things for you:
- Adds or removes the
darkclass on the<html>element. - Saves the selected theme in
localStorage. - Supports a
systemoption that follows the visitor's operating system preference. - Runs a small script before the page is displayed so the saved theme can be applied early.
That last point helps prevent a flash of the wrong theme when the page loads. If you wait until a React useEffect runs to apply the theme, the browser may display the page before the effect runs. A visitor who prefers dark mode could briefly see the light version first.
The generated project already includes a theme provider and mounts it in the app layout. Let's take a look at what it does.
6. The Theme Provider That's Already in Your Project
The generated components/theme-provider.tsx file wraps next-themes and sets a few defaults. Here's the provider from the companion project:
"use client" import * as React from "react" import { ThemeProvider as NextThemesProvider, useTheme } from "next-themes" function ThemeProvider({ children, ...props }: React.ComponentProps<typeof NextThemesProvider>) { return ( <NextThemesProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange {...props} > <ThemeHotkey /> {children} </NextThemesProvider> ) } The wrapper means you don't need to repeat the same configuration every time you use the provider. In app/layout.tsx, it can be mounted like this:
<ThemeProvider>{children}</ThemeProvider> The {...props} spread comes after the default props. That means a value passed to ThemeProvider can override the wrapper's defaults.
There's a Keyboard Shortcut Too
The provider file also includes a ThemeHotkey component:
function isTypingTarget(target: EventTarget | null) { if (!(target instanceof HTMLElement)) { return false } return ( target.isContentEditable || target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT" ) } function ThemeHotkey() { const { resolvedTheme, setTheme } = useTheme() React.useEffect(() => { function onKeyDown(event: KeyboardEvent) { if (event.defaultPrevented || event.repeat) return if (event.metaKey || event.ctrlKey || event.altKey) return if (event.key.toLowerCase() !== "d") return if (isTypingTarget(event.target)) return setTheme(resolvedTheme === "dark" ? "light" : "dark") } window.addEventListener("keydown", onKeyDown) return () => window.removeEventListener("keydown", onKeyDown) }, [resolvedTheme, setTheme]) return null } This component doesn't render anything on the page. It listens for the d key and switches between light and dark mode.
Notice the checks inside the keyboard handler. They prevent the shortcut from firing when the user is typing in an input, textarea, select, or editable element. The modifier-key check also prevents the shortcut from interfering with combinations such as Cmd+D or Ctrl+D.
If you don't want this shortcut in your project, remove <ThemeHotkey /> from the provider. If you keep it, consider mentioning it somewhere in your app so users know it's available.
What the Provider Options Mean
| Option | Purpose |
|---|---|
attribute="class" | Adds a class to <html> instead of a data-theme attribute. |
defaultTheme="system" | Uses the operating system preference for a first-time visitor. |
enableSystem | Enables the system theme option. |
disableTransitionOnChange | Temporarily disables CSS transitions while the theme changes. |
The attribute="class" setting needs to match the CSS setup from the earlier section. The generated stylesheet looks for .dark, so next-themes needs to add a class. If you change the attribute to data-theme, the .dark selector won't match unless you also update your CSS.
If your switcher uses animated icons, this setting can affect their transitions. The behavior is worth considering when you decide how theme changes should look across the page.
Why layout.tsx Uses suppressHydrationWarning
You may also notice this on the <html> element in app/layout.tsx:
<html lang="en" suppressHydrationWarning className={cn("antialiased", …)}> The theme script can update the <html> class before React hydrates the page. That means the HTML rendered on the server may have a different class from the HTML React sees in the browser.
suppressHydrationWarning tells React to suppress that expected warning on this element. It's included in the generated setup for this reason. It applies to that element, rather than disabling hydration warnings throughout the app.
7. Build a Theme Switcher
At this point, the theme colors are configured and next-themes can apply the selected theme. What the project still needs is a visible control that lets users change it.
There are two common approaches. You can give users a button that switches between light and dark, or offer a menu with Light, Dark, and System options.
Option 1: A light and Dark Toggle
If your app only needs two modes, a single button is enough:
"use client" import { Moon, Sun } from "lucide-react" import { useTheme } from "next-themes" import { Button } from "@/components/ui/button" function ModeSwitch() { const { resolvedTheme, setTheme } = useTheme() return ( <Button variant="ghost" size="icon" aria-label="Toggle theme" onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")} > <Sun className="dark:hidden" /> <Moon className="hidden dark:block" /> </Button> ) } export { ModeSwitch } A few details in this component are worth understanding.
First, use resolvedTheme for a two-state toggle. The theme value can be "system", while resolvedTheme tells you which theme is currently active: "light" or "dark". Since this button switches between two visible states, resolvedTheme is the value you want to check.
Second, keep both icons in the DOM. The Sun and Moon icons are shown or hidden with CSS classes. This avoids choosing an icon based on a theme value that may not be available during server rendering.
For comparison, this conditional approach can cause a mismatch between the server-rendered markup and the browser's first render:
{resolvedTheme === "dark" ? <Moon /> : <Sun />} Finally, add an accessible label. Since the button only contains an icon, aria-label gives screen reader users a useful description of what the button does.
Option 2: A Light, Dark, and System Menu
If you want users to choose their preferred mode, including the operating system setting, use a dropdown menu.
First, add the dropdown menu component if it's not already in your project:
pnpm dlx shadcn@latest add dropdown-menu Then create the switcher:
"use client" import { ChevronDown, Monitor, Moon, Sun } from "lucide-react" import { useTheme } from "next-themes" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" const MODES = [ { value: "light", label: "Light", icon: Sun }, { value: "dark", label: "Dark", icon: Moon }, { value: "system", label: "System", icon: Monitor }, ] function ModeToggle() { const { theme, setTheme } = useTheme() return ( <DropdownMenu> <DropdownMenuTrigger render={<Button variant="ghost" aria-label="Change theme" />} > <Sun className="dark:hidden" /> <Moon className="hidden dark:block" /> <ChevronDown className="size-3 text-muted-foreground" /> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="min-w-36"> <DropdownMenuRadioGroup value={theme ?? "system"} onValueChange={(value) => setTheme(value as string)} > {MODES.map(({ value, label, icon: Icon }) => ( <DropdownMenuRadioItem key={value} value={value}> <Icon className="text-muted-foreground" /> {label} </DropdownMenuRadioItem> ))} </DropdownMenuRadioGroup> </DropdownMenuContent> </DropdownMenu> ) } export { ModeToggle } The menu uses a radio group so the current option is shown as selected. This makes it easier for users to see whether Light, Dark, or System is active.
There are two implementation details to pay attention to here.
First, base UI uses render instead of asChild. The companion project uses the base-nova style, which is built on Base UI. In this setup, the dropdown trigger uses the render prop to render the shadcn button. Many older examples use asChild, which is common in Radix-based projects. Check your own components.json and component imports before copying an example.
Use a radio group for mutually exclusive options. Light, Dark, and System are three choices where only one can be active at a time. DropdownMenuRadioGroup communicates that relationship and displays the selected option.
The expression theme ?? "system" uses "system" as a fallback if the theme value is still undefined. This keeps the radio group controlled while next-themes initializes.
You may have seen the next-themes advice to wait until a component has mounted before rendering anything based on theme. That advice is for UI the server renders. Here, the radio items only appear when someone opens the menu, which always happens after the page has hydrated, so the server never renders a theme value and there's nothing to mismatch.
You can now place the switcher in your header or another part of your layout. For example:
import { ModeToggle } from "@/components/mode-toggle" <header className="flex h-14 items-center justify-between border-b px-6"> <h1 className="text-sm font-medium">My app</h1> <ModeToggle /> </header> Choose one switcher for your app, based on how much control you want to give users. You don't need to display both versions at once.
The switcher will usually sit inside a larger page, such as an account settings screen or dashboard. If you're building that kind of page, shadcn blocks can give you useful layout examples. You can adapt a block to your needs and keep using the same theme tokens for its backgrounds, borders, and text.
8. Why the Icon Animation May Not Work
You might want the sun and moon icons to rotate or scale when someone changes the theme. The shadcn examples include transition classes like these:
<Sun className="scale-100 rotate-0 transition-transform dark:scale-0 dark:-rotate-90" /> <Moon className="absolute scale-0 rotate-90 transition-transform dark:scale-100 dark:rotate-0" /> But the generated provider also uses disableTransitionOnChange. This option temporarily injects a stylesheet that disables transitions while the theme is changing. The rule used by the installed next-themes version is:
*,*::before,*::after{transition:none!important} Because the rule uses !important, it can override the transition-transform classes on the icons during the theme change. The icons may switch immediately instead of animating.
There's a reason this option exists. Without it, every element with a CSS transition may animate its colors when the theme changes. Depending on your design, that can make the entire page feel slow or distracting.
You have a few options:
- Keep
disableTransitionOnChangeand use icons without transition effects. - Remove the option if you want the page and icons to transition together.
- Keep the option and use a CSS animation or a motion library for the icon effect. Test this with your actual setup to make sure the animation behaves as expected.
The important thing is to understand that the provider setting affects more than the theme colors. It can also affect transitions elsewhere in your interface.
9. Customize Your Theme
Once you understand where the theme values live, changing your app's colors becomes much easier. You can update a token once and have every component that uses it pick up the new value.
Change an Existing Token
Imagine your brand uses blue as its primary color. You could set a blue background directly on one button:
<Button className="bg-blue-500 dark:bg-blue-700">Save</Button> But this only changes that button. If you want the primary color to be consistent across your app, update the --primary token in app/globals.css instead:
:root { --primary: oklch(0.55 0.18 265); --primary-foreground: oklch(0.99 0 0); } .dark { --primary: oklch(0.62 0.16 265); --primary-foreground: oklch(0.17 0.02 265); } The same token is used by components and utilities throughout the project. Update both the :root and .dark values so the color works in both themes.
The two values don't have to be identical. A color that looks good on a light background may need a different lightness or saturation on a dark background. The generated theme uses different values for some tokens for exactly this reason.
The project also uses oklch() color values. In this color format, the first value represents lightness, which can make it easier to adjust how bright or dark a color appears while keeping its hue consistent.
You can customize the border radius in the same way. The generated @theme inline block derives several radius utilities from the --radius value, so changing it updates the overall corner scale:
--radius: 0.625rem; Add a Custom Token
You can also add tokens that aren't included in the default theme. For example, let's add a warning color that can be used for a notice or alert.
First, define the token and its foreground color in both theme blocks. Then connect those variables to Tailwind in @theme inline:
:root { --warning: oklch(0.84 0.16 84); --warning-foreground: oklch(0.28 0.07 46); } .dark { --warning: oklch(0.41 0.11 46); --warning-foreground: oklch(0.99 0.02 95); } @theme inline { --color-warning: var(--warning); --color-warning-foreground: var(--warning-foreground); } You can now use the new classes in a component:
<div className="bg-warning text-warning-foreground rounded-lg p-3"> Your trial ends in 3 days. </div> The component uses the same classes in both screenshots. The theme supplies the appropriate background and text colors.
Remember to add the --color-warning and --color-warning-foreground entries to @theme inline. Without those entries, the CSS variables will exist, but Tailwind won't generate the corresponding utility classes.
It's also a good idea to define a foreground token whenever you add a new surface color. That way, the background and text colors are designed to work together.
When Should You Use dark:
Once your theme uses semantic tokens, you won't need dark: classes for most background and text colors.
For example, instead of maintaining separate light and dark background classes:
// You're now maintaining this color in two places <div className="bg-slate-100 dark:bg-slate-800"> // The token already knows <div className="bg-muted"> Use a semantic token such as bg-muted when it represents the color you want. The token already has values for both themes.
There are still cases where dark: is useful. You might need to swap an image, adjust a shadow, or change a decorative element that doesn't fit into your semantic color tokens. Use it when the appearance genuinely needs a theme-specific rule.
Conclusion
A generated shadcn project already includes most of the setup needed for light and dark mode. The part you usually need to build is the switcher that gives users control over the theme.
Here's a quick recap:
:rootand.darkdefine the theme values. They use the same variable names with different values.@theme inlineconnects CSS variables to Tailwind utilities**.** Add a matching entry when you create a custom token.next-themesapplies the active theme. In this setup, it adds or removes thedarkclass on<html>.- The generated project already includes the provider. Check
components/theme-provider.tsxandapp/layout.tsxbefore creating another one. - The visible switcher is the part you add. Use a simple toggle or a menu with Light, Dark, and System options.
- Customize tokens instead of styling every component separately. This keeps your colors consistent across the app.
Once you know how these pieces fit together, dark mode becomes easier to maintain. You can update the theme in one place, add new tokens when you need them, and let your components use those values without having to check which theme is active.
References
- shadcn/create: Generate a shadcn project.
- shadcn dark mode for Next.js: Official Next.js dark-mode setup.
- shadcn theming: Theme tokens and CSS variables.
- next-themes: Theme provider documentation and source.
- Tailwind CSS theme variables: How theme variables create utility classes.
- Base UI: Documentation for the primitives used by the
base-novastyle. - MDN:
oklch(): Reference for the OKLCH color format.
Thanks for Reading
The companion project includes both switcher examples, the custom warning token, and the page used for the screenshots. To try the examples locally, clone the repository, then run pnpm install followed by pnpm dev from the project directory.
Companion GitHub repository:- https://github.com/shadcnstudio/shadcn-dark-mode-guide
If you try the examples and run into something that behaves differently in your setup, leave a comment with your shadcn style and package versions. That context makes it much easier to work out what's happening.