# Indicación para agregar modo oscuro con Tailwind CSS v4

> Indicación para agente de IA para agregar modo oscuro consciente del sistema a una aplicación Next.js usando variables CSS de Tailwind CSS v4 y next-themes, sin destello al cargar.

**Type:** Prompt  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Next.js, TypeScript, Tailwind  
**Difficulty:** easy  
**Updated:** 2026-06-08

---

Entrega esta indicación a tu agente para agregar modo oscuro usando el sistema de variables CSS de Tailwind v4 y `next-themes` — evitando el destello de contenido sin estilo que afecta a las implementaciones ingenuas de `localStorage`.

## Indicación principal

```txt title="Main Prompt"
You are working in a Next.js App Router project with TypeScript and Tailwind CSS v4.

Task: add dark mode with system preference detection and a manual toggle.

Requirements:
- Install `next-themes`.
- In `src/app/layout.tsx`, wrap the app in `<ThemeProvider attribute="class" defaultTheme="system" enableSystem>`.
  The `ThemeProvider` is a Client Component — create a wrapper `src/components/Providers.tsx` if
  the root layout must remain a Server Component.
- In `src/styles/global.css`, define CSS custom properties for both themes using the Tailwind v4
  `@theme` directive:
    - Light: `--color-bg: oklch(100% 0 0)`, `--color-text: oklch(9% 0 0)`.
    - Dark (inside `[class="dark"]` selector): override those variables.
  Apply them to the body as `background: var(--color-bg)` and `color: var(--color-text)`.
- Create `src/components/ThemeToggle.tsx` (Client Component) using `useTheme` from `next-themes`.
  It should cycle through light → dark → system on click and show a sun/moon/monitor icon.
  Use Tailwind's built-in `dark:` variant for icon visibility — do NOT use conditional classNames
  based on the `theme` string for icon color.
- Do not use `tailwind.config.ts` `darkMode: 'class'` — that is Tailwind v3 API. In v4, the
  `dark:` variant is class-based by default.
- Do NOT install lucide-react or any icon library — use SVG inline.

Stop and list all planned file changes before writing any code.
```

## Notas de implementación

- En Tailwind v4, el modo oscuro mediante el prefijo `dark:` funciona automáticamente con la clase `.dark` en `html` — no se necesita entrada de configuración.
- `next-themes` lee el tema guardado de `localStorage` y establece la clase antes del primer pintado, lo que previene el FOUC.
- El `ThemeProvider` debe estar en el lado del cliente, pero el `layout.tsx` raíz puede permanecer del lado del servidor extrayendo el proveedor a un componente envoltorio `Providers.tsx` marcado como `'use client'`.

## Cambios esperados en archivos

```txt
src/app/layout.tsx                     (edited — add Providers wrapper)
src/components/Providers.tsx           (new — Client Component with ThemeProvider)
src/components/ThemeToggle.tsx         (new — Client Component)
src/styles/global.css                  (edited — CSS custom properties for light/dark)
package.json                           (edited — add next-themes)
```

## Criterios de aceptación

- En la primera carga con el sistema configurado en oscuro, la página se renderiza oscura sin destello.
- Alternar ThemeToggle recorre los modos claro, oscuro y sistema; la preferencia persiste al recargar.
- Todas las utilidades `dark:` de Tailwind existentes funcionan sin cambios de configuración.
- `bun run build` termina con código 0.

## Comandos de prueba

```bash
bun add next-themes
bun run typecheck
bun run build
bun run dev
# open DevTools, set system dark mode, reload — confirm no white flash
# click ThemeToggle three times and confirm cycle: light → dark → system
```

## Errores comunes de IA

- Agregar `darkMode: 'class'` a un `tailwind.config.ts` que no existe en un proyecto v4.
- Envolver el Server Component raíz `layout.tsx` con `'use client'` en lugar de extraer un componente Providers.
- Usar renderizado condicional `theme === 'dark'` en lugar de la variante `dark:` de Tailwind, causando discrepancias de hidratación.
- Olvidar `enableSystem` en `ThemeProvider`, haciendo que la detección de preferencia del sistema no funcione.

## Indicación de corrección

```txt title="Fix Prompt"
There's a white flash on load or a hydration mismatch. Fix in order:
1. Ensure `ThemeProvider` has `attribute="class"` and `enableSystem` props.
2. Make sure `Providers.tsx` (not `layout.tsx`) is marked `'use client'`.
3. Remove any `theme === 'dark'` conditional rendering from `ThemeToggle` — use `dark:` Tailwind
   variants instead so the server and client render the same HTML.
Show only the corrected diff.
```