Tailwind CSS Colors in Next.js Projects
Best practices for using Tailwind colors in Next.js with App Router, Server Components, and theme management.
nextjsapp-routerserver-componentstheming
intermediate12 min readtutorial
Setting Up Tailwind Colors in Next.js
Next.js has first-class Tailwind support. With the App Router, you need to handle color theming carefully since Server Components cannot access browser APIs like localStorage for theme preferences.
Global Color Configuration
// app/globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 222 47% 11%;
--primary: 221 83% 53%;
--muted: 210 40% 96%;
}
.dark {
--background: 222 47% 11%;
--foreground: 210 40% 98%;
--primary: 217 91% 60%;
--muted: 217 33% 17%;
}
}Theme Provider for App Router
// app/providers.tsx
'use client';
import { ThemeProvider } from 'next-themes';
export function Providers({ children }) {
return (
<ThemeProvider attribute="class" defaultTheme="system">
{children}
</ThemeProvider>
);
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({ children }) {
return (
<html lang="en" suppressHydrationWarning>
<body className="bg-background text-foreground">
<Providers>{children}</Providers>
</body>
</html>
);
}Server vs Client Color Logic
- Server Components: Use static Tailwind classes only, no dynamic theme logic
- Client Components: Use 'use client' directive for interactive color changes
- CSS variables bridge the gap by letting server-rendered HTML adapt via cascading styles
- Use next-themes to prevent flash of wrong theme on load
Frequently Asked Questions
How do I prevent a flash of unstyled theme in Next.js?
Use next-themes with the attribute='class' option and add suppressHydrationWarning to your html tag. The library injects a script to set the theme before React hydrates.
Can I use Tailwind colors in Next.js API routes?
API routes run on the server and return data, not UI. Tailwind classes are only relevant in components. However, you can reference your color tokens in API responses if needed for client rendering.
Try Our Color Tools
50+ free tools for Tailwind CSS developers. No signup required.
Explore Tools