Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

themes

> 编程语言
Open source

A modern, fully-featured theme management library for Next.js

100 stars0 likes2 views
WebsiteGitHub

About

A modern, fully-featured theme management library for Next.js

@wrksz/themes

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. npm latest remains 1.2.0 until 2.0 is stable.

Breaking vs 1.2.0: Next ThemeProvider no longer calls cookies() (sync App Shell provider); pass initialTheme via getTheme() when SSR markup needs the cookie; TypeScript peer >=5.9; forcedTheme does not persist; sticky mount init for initialTheme/storageKey. Full guide: Upgrading from 1.x.

bash
bun add @wrksz/themes@beta
# or
npm install @wrksz/themes@beta
# stable 1.x:
# npm install @wrksz/[email protected]

Why not 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 ✅ ✅

Table of Contents

  • Setup
  • Usage
  • Zero-flash SSR with cookie storage
  • Security model
  • API
    • ThemeProvider
    • useTheme
    • getTheme
    • useThemeValue
    • ThemedImage
  • Examples
  • Import paths

Setup

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.

typescript
// app/layout.tsx
import { ThemeProvider } from "@wrksz/themes/next";

export default function RootLayout({ children }: { children: React.ReactNode }) {
	return (
		
			
				{children}
			
		
	);
}

Note: Use ThemeProvider from @wrksz/themes/next directly in a server layout.tsx. For nested providers inside Client Components, use ClientThemeProvider.

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.

Usage

typescript
"use client";

import { useTheme } from "@wrksz/themes/client";

export function ThemeToggle() {
	const { resolvedTheme, setTheme } = useTheme();

	return (
		 setTheme(resolvedTheme === "dark" ? "light" : "dark")}>
			Toggle theme
		
	);
}

Zero-flash SSR with cookie storage

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:

typescript
// 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:

css
/* ❌ 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 localStorage with initialTheme if you need it.

Security model

@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.

API

ThemeProvider

The canonical prop table lives on the docs site: ThemeProvider.

typescript
import { ThemeProvider } from "@wrksz/themes/next";

Opt-in extended provider

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:

typescript
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:

typescript
"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.

useTheme

typescript
const {
	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:

typescript
type AppTheme = "light" | "dark" | "high-contrast";

const { theme, setTheme } = useTheme();
// theme: AppTheme | "system" | undefined
// setTheme: (theme: AppTheme | "system") => void

getTheme

Reads the current theme from a cookie outside React. Available in @wrksz/themes/next.

typescript
// 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:

typescript
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

useThemeValue

Returns the value from a map matching the current resolved theme. Returns undefined before the theme resolves on the client.

typescript
"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:  });

useThemeEffect

Runs an effect after mount whenever the theme changes:

typescript
"use client";
import { useThemeEffect } from "@wrksz/themes/client";

useThemeEffect((theme, resolvedTheme) => {
	trackThemeChange(theme, resolvedTheme);
});

createThemes

Create a typed theme module once and reuse it everywhere:

typescript
"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.

ThemedImage

Shows different images per theme. Renders a transparent placeholder on the server to avoid hydration mismatches.

typescript
import { ThemedImage } from "@wrksz/themes/client";

;

Examples

Custom themes

typescript
{children}

Data attribute instead of class

typescript
{children}
css
[data-theme="dark"] {
	--bg: #000;
}
[data-theme="light"] {
	--bg: #fff;
}

Multiple classes per theme

typescript

	{children}

Switching away from "dark" correctly removes both dark and high-contrast.

Forced theme per page

typescript
// app/dashboard/layout.tsx
{children}

Scoped theming

Apply the theme to a specific element instead of ``, so different sections can have independent themes simultaneously:

typescript

	
css
#landing-root {
	--bg: #0a0a0a;
	--fg: #fafafa;
}

Server-provided theme

Initialize from a server-side source (database, s

Issues· 13 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言