A modern, fully-featured theme management library for Next.js
A modern, fully-featured theme management library for Next.js
Modern theme management for Next.js 16+ and React 18+. Near drop-in replacement for next-themes - fixes every known bug and adds missing features, including native useEffectEvent integration on React 19.2+. Migrating requires changing one import line.
TypeScript 5.9 or newer is required. TypeScript 5.9, 6, and 7 are supported and checked against the published package declarations in CI.
2.0.0-beta.1: install with@wrksz/themes@beta. npmlatestremains 1.2.0 until 2.0 is stable.Breaking vs 1.2.0: Next
ThemeProviderno longer callscookies()(sync App Shell provider); passinitialThemeviagetTheme()when SSR markup needs the cookie; TypeScript peer>=5.9;forcedThemedoes not persist; sticky mount init forinitialTheme/storageKey. Full guide: Upgrading from 1.x.
bun add @wrksz/themes@beta
# or
npm install @wrksz/themes@beta
# stable 1.x:
# npm install @wrksz/[email protected]next-themes?| next-themes | @wrksz/themes | |
|---|---|---|
| React 19 script warning | ❌ | ✅ useServerInsertedHTML |
__name minification bug |
❌ | ✅ |
Stale theme with React 19 cacheComponents |
❌ | ✅ useSyncExternalStore |
| Multi-class theme removal leaving stale classes | ❌ | ✅ |
| Nested providers | ❌ | ✅ per-instance store |
sessionStorage support |
❌ | ✅ |
cookie storage (zero-flash SSR) |
❌ | ✅ |
hybrid storage (SSR + cross-tab sync) |
❌ | ✅ |
| Disable storage | ❌ | ✅ storage="none" |
meta theme-color support |
❌ | ✅ themeColor prop |
| Server-provided theme | ❌ | ✅ initialTheme prop |
disableTransitionOnChange per property |
❌ | ✅ pass a CSS string |
| Read theme outside React | ❌ | ✅ getTheme() helper |
| Generic types | ❌ | ✅ useTheme() |
| Typed factory | ❌ | ✅ createThemes(...) |
| Theme-change effect hook | ❌ | ✅ useThemeEffect(...) |
| Hydration state without mount effects | ❌ | ✅ useHydrated() |
| Framework-neutral SSR bootstrap | ❌ | ✅ @wrksz/themes/script |
| Zero runtime dependencies | ✅ | ✅ |
Add the provider to your root layout. Import from @wrksz/themes/next for Next.js - this avoids the React 19 inline script warning by using useServerInsertedHTML. Add suppressHydrationWarning to `` to prevent hydration mismatches.
// app/layout.tsx
import { ThemeProvider } from "@wrksz/themes/next";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}Note: Use
ThemeProviderfrom@wrksz/themes/nextdirectly in a serverlayout.tsx. For nested providers inside Client Components, useClientThemeProvider.
The Next provider is static and compatible with Next.js 16.3 Instant Navigations,
cacheComponents, and Partial Prefetching. It does not mutate cookies during prefetches.
Use getTheme() only when server-rendered markup must depend on the cookie; under Cache
Components, isolate that request-time read with Suspense or opt the route out with
export const instant = false.
"use client";
import { useTheme } from "@wrksz/themes/client";
export function ThemeToggle() {
const { resolvedTheme, setTheme } = useTheme();
return (
setTheme(resolvedTheme === "dark" ? "light" : "dark")}>
Toggle theme
);
}Use storage="cookie" with @wrksz/themes/next to eliminate theme flash. The static bootstrap reads the cookie synchronously before paint, so the provider remains compatible with Next.js 16.3 App Shells and Partial Prefetching:
// app/layout.tsx
import { ThemeProvider } from "@wrksz/themes/next";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
{children}
);
}For apps using CSS media queries (@media (prefers-color-scheme: dark)) alongside CSS class variables, avoid the media query fallback - the library sets the correct class before the first paint:
/* ❌ causes flash when system pref differs from stored theme */
@media (prefers-color-scheme: dark) {
:root:not(.light) {
--bg: #09090b;
}
}
/* ✅ */
:root {
--bg: #ffffff;
}
:root.dark {
--bg: #09090b;
}Cookie storage does not support cross-tab theme sync. Use
localStoragewithinitialThemeif you need it.
@wrksz/themes injects a small inline script so the correct theme can be applied before
React hydrates. Script config is serialized with script-context escaping, so values such as
themeColor, value, themes, forcedTheme, and initialTheme cannot break out of the
payloads.
If your app uses a Content Security Policy, pass a request-scoped nonce to ThemeProvider
and include the same nonce in your script-src policy.
Cookie storage treats cookies as untrusted input: stored values are validated against
themes when a theme list is provided, malformed cookie encoding falls back to
defaultTheme, and cookie attributes are validated before writes. Releases are published
with npm provenance from GitHub Actions.
ThemeProviderThe canonical prop table lives on the docs site: ThemeProvider.
import { ThemeProvider } from "@wrksz/themes/next";The default provider stays intentionally small. Import the extended provider only when you need
same-document synchronization, custom system mappings, or a client-owned Element/ShadowRoot:
import { ThemeProvider } from "@wrksz/themes/next/extended";
{children}
;The Next.js extended provider is synchronous and does not read cookies on the
server. It supports the serializable systemThemeMap and
enableSameDocumentSync props. For a DOM object, use the client-only entry:
"use client";
import { ClientThemeProvider } from "@wrksz/themes/client/extended-provider";
{children}
;enableSameDocumentSync?: boolean synchronizes providers with the same storage key.systemThemeMap?: { light: Theme; dark: Theme } | Record
maps system preferences to custom names or preserves variant families.themeRoot?: Element | ShadowRoot targets a client-owned element or a ShadowRoot host. Worked example: Shadow DOM.useThemeconst {
theme, // Current theme - may be "system"
resolvedTheme, // Actual theme - never "system"
systemTheme, // System preference: "light" | "dark" | undefined
forcedTheme, // Forced theme if set
themes, // Available themes
setTheme, // Set theme
} = useTheme();Supports generics for full type safety:
type AppTheme = "light" | "dark" | "high-contrast";
const { theme, setTheme } = useTheme();
// theme: AppTheme | "system" | undefined
// setTheme: (theme: AppTheme | "system") => voidgetThemeReads the current theme from a cookie outside React. Available in @wrksz/themes/next.
// proxy.ts - sync, reads from Request
import { getTheme } from "@wrksz/themes/next";
export function proxy(request: Request) {
const theme = getTheme(request, { defaultTheme: "dark" });
}
// layout.tsx - async, reads via cookies() from next/headers
const theme = await getTheme({ defaultTheme: "dark" });
return ...;Pass themes as a readonly tuple to infer the return type:
const theme = getTheme(request, {
themes: ["light", "dark", "high-contrast"] as const,
defaultTheme: "light",
});
// theme: "light" | "dark" | "high-contrast"| Option | Type | Default | Description |
|---|---|---|---|
storageKey |
string |
"theme" |
Cookie name to read from |
defaultTheme |
string |
"system" |
Returned when no valid theme is found |
themes |
readonly string[] |
- | When provided, stored values not in the list fall back to defaultTheme. Use as const for return type inference |
useThemeValueReturns the value from a map matching the current resolved theme. Returns undefined before the theme resolves on the client.
"use client";
import { useThemeValue } from "@wrksz/themes/client";
const label = useThemeValue({ light: "Switch to dark", dark: "Switch to light" });
const bg = useThemeValue({ light: "#ffffff", dark: "#0a0a0a" });
const icon = useThemeValue({ light: , dark: });useThemeEffectRuns an effect after mount whenever the theme changes:
"use client";
import { useThemeEffect } from "@wrksz/themes/client";
useThemeEffect((theme, resolvedTheme) => {
trackThemeChange(theme, resolvedTheme);
});createThemesCreate a typed theme module once and reuse it everywhere:
"use client";
import { createThemes } from "@wrksz/themes/client";
export const { ThemeProvider, useTheme, useThemeValue, useThemeEffect } = createThemes({
themes: ["light", "dark", "high-contrast"] as const,
storage: "hybrid",
defaultTheme: "system",
attribute: "class",
});For a Next.js root layout, import from @wrksz/themes/next/create-themes and use NextThemeProvider so the theme tuple is not copied into @wrksz/themes/next. Full API: createThemes.
ThemedImageShows different images per theme. Renders a transparent placeholder on the server to avoid hydration mismatches.
import { ThemedImage } from "@wrksz/themes/client";
;{children}{children}[data-theme="dark"] {
--bg: #000;
}
[data-theme="light"] {
--bg: #fff;
}
{children}
Switching away from "dark" correctly removes both dark and high-contrast.
// app/dashboard/layout.tsx
{children}Apply the theme to a specific element instead of ``, so different sections can have independent themes simultaneously:
#landing-root {
--bg: #0a0a0a;
--fg: #fafafa;
}Initialize from a server-side source (database, s
No open issues yet, or sync has not completed.