### Basic setup with default options Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of basic ThemeProvider setup in a Next.js RootLayout. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Install Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Install next-themes using npm or yarn. ```bash $ npm install next-themes # or $ yarn add next-themes ``` -------------------------------- ### Installation Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/README.md Install the next-themes library using npm or yarn. ```bash npm install next-themes # or yarn add next-themes ``` -------------------------------- ### Complete configuration example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md This example shows a complete configuration for the ThemeProvider component, including various props for theme management, system preference handling, color scheme, transitions, storage, attributes, and nonce. ```tsx {children} ``` -------------------------------- ### themes Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Examples of how to configure the `themes` prop. ```tsx // Default behavior {/* Available themes: light, dark, system */} // Custom themes (replaces defaults) {/* Available themes: pink, blue, green, system */} // Keep light/dark and add custom themes {/* Available themes: light, dark, pink, blue, system */} ``` -------------------------------- ### Basic Setup Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/README.md Set up the ThemeProvider in your root layout component. ```tsx import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### useTheme hook Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example of using the useTheme hook to get the current theme and change it. ```jsx import { useTheme } from 'next-themes' const ThemeChanger = () => { const { theme, setTheme } = useTheme() return (
The current theme is: {theme}
) } ``` -------------------------------- ### HTML & CSS Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example CSS for styling your app based on the data-theme attribute. ```css :root { /* Your default theme */ --background: white; --foreground: black; } [data-theme='dark'] { --background: black; --foreground: white; } ``` -------------------------------- ### CSP Compatibility Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-script.md Example of how to use the nonce prop for Content Security Policy compatibility. ```tsx ``` -------------------------------- ### Defining multiple themes Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example of passing a list of themes to the ThemeProvider. ```jsx ``` -------------------------------- ### CSP Header Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Illustrates a Content Security Policy header that includes a nonce for scripts. ```text Content-Security-Policy: script-src 'nonce-abc123def456' ``` -------------------------------- ### Children Prop Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Demonstrates how to wrap child components with the ThemeProvider to enable theme context. ```tsx
``` -------------------------------- ### Script Props Examples Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Examples of passing additional HTML attributes to the injected script tag, such as disabling Cloudflare Rocket Loader or adding an ID. ```tsx // Disable Cloudflare Rocket Loader {children} // Add multiple data attributes {children} // Add script ID for debugging {children} ``` -------------------------------- ### defaultTheme Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Examples of how to configure the `defaultTheme` prop. ```tsx // Use system preference by default {/* defaultTheme is 'system' */} // Always start with light theme {/* No system preference detection */} // Start with a custom theme // Explicitly set to system even though enableSystem will be true ``` -------------------------------- ### ValueObject Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/types.md Example of a ValueObject mapping theme names to DOM attribute values. ```typescript // Theme name "dark" will be stored in localStorage as "dark", // but the DOM will have the value "my-dark-theme" instead { dark: 'my-dark-theme', light: 'my-light-theme' } ``` -------------------------------- ### useTheme Called Outside Provider - Right Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of correct component structure with ThemeProvider at the root. ```tsx // ✓ Right - ThemeProvider at root function App() { return (
{/* Can use useTheme */}
{/* Can use useTheme */} ) } ``` -------------------------------- ### Styling without CSS variables Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example CSS demonstrating how to style themes without relying on CSS variables. ```css html, body { color: #000; background: #fff; } [data-theme='dark'], [data-theme='dark'] body { color: #fff; background: #000; } ``` -------------------------------- ### More than light and dark mode Source: https://github.com/pacocoursey/next-themes/blob/main/README.md Example of how to define custom themes. ```jsx ``` ```jsx ``` -------------------------------- ### Nonce for CSP Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Example of how to provide a nonce for Content Security Policy to allow injected scripts and styles. ```tsx // Server component that generates a nonce export default function RootLayout({ children, nonce }) { return ( {children} ) } // Nonce is usually generated per-request // Example with Next.js headers: // const nonce = crypto.randomUUID() ``` -------------------------------- ### forcedTheme Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Examples of how to use the `forcedTheme` prop. ```tsx // Force dark theme on entire app {children} // Force a specific theme on a page // In pages/dark-only-page.tsx export default function Page() { return ( ) } // Dynamically force theme based on conditions {children} ``` ```tsx const { forcedTheme } = useTheme() if (forcedTheme) { return
Theme is locked to {forcedTheme}
} ``` -------------------------------- ### ScriptProps Common Usage Examples Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/types.md Common usage examples for ScriptProps. ```typescript // { 'data-cfasync': 'false' } — disables Cloudflare Rocket Loader on the script // { async: true } — loads script asynchronously (though the default no-load behavior is preferred) // { id: 'next-themes-script' } — adds an ID to the script for targeting ``` -------------------------------- ### Mismatched Configuration Example (Correct) Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Shows the correct way to configure ThemeProvider to manage attributes. ```tsx // ✓ Right - Let ThemeProvider manage both {children} ``` -------------------------------- ### Including default themes when defining multiple themes Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example showing how to include the default 'light' and 'dark' themes when defining a custom list of themes. ```jsx ``` -------------------------------- ### Pages Directory _app.tsx Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-overview.md Example of integrating ThemeProvider in the Pages Directory _app.tsx file. ```tsx // pages/_app.tsx import { ThemeProvider } from 'next-themes' function MyApp({ Component, pageProps }) { return ( ) } export default MyApp ``` -------------------------------- ### App Directory Layout Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-overview.md Example of integrating ThemeProvider in the App Directory layout. ```tsx // app/layout.tsx 'use client' import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### useTheme Called Outside Provider - Wrong Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of incorrect component structure where ThemeProvider is not at the root. ```tsx // ✗ Wrong - ThemeProvider is not at root function App() { return (
{/* Can't use useTheme here */}
{/* Can use useTheme */} ) } ``` -------------------------------- ### Setup with Tailwind CSS Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Configuring ThemeProvider to work with Tailwind CSS by setting the attribute to 'class'. ```tsx {children} ``` -------------------------------- ### Value Mapping Examples Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Demonstrates how to map internal theme names to different DOM attribute values for CSS class names or data attributes. ```tsx // Without value mapping {/* localStorage: "dark", DOM: data-theme="dark" */} // With value mapping {/* localStorage: "dark", DOM: data-theme="dark-mode" */} // Map to Tailwind class names {/* localStorage: "dark", DOM: class="dark" */} // Map custom theme names to class names {/* localStorage: "slate", DOM: class="slate-theme" */} ``` -------------------------------- ### Multiple Custom Themes Setup Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/recipes.md Configures and uses multiple custom themes beyond just light and dark. ```typescript // app/layout.tsx import { ThemeProvider } from 'next-themes' const themes = ['light', 'dark', 'blue', 'purple', 'rose'] export default function RootLayout({ children }) { return ( {children} ) } // theme-selector.tsx import { useTheme } from 'next-themes' export function ThemeSelector() { const [mounted, setMounted] = useState(false) const { theme, setTheme, themes } = useTheme() useEffect(() => { setMounted(true) }, []) if (!mounted) return null return (
{themes.map((t) => ( ))}
) } ``` -------------------------------- ### Typical Usage Pattern Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-overview.md Example of wrapping the application with ThemeProvider and using the useTheme hook in a component. ```tsx import { ThemeProvider, useTheme } from 'next-themes' // 1. Wrap app with provider export default function RootLayout({ children }) { return ( {children} ) } // 2. Use hook in components function ThemeSwitcher() { const { theme, setTheme, themes } = useTheme() return ( ) } ``` -------------------------------- ### With CSP nonce Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of using ThemeProvider with a CSP nonce for security. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Using with Styled Components Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example of integrating next-themes with Styled Components using createGlobalStyle in the custom App. ```jsx // pages/_app.js import { createGlobalStyle } from 'styled-components' import { ThemeProvider } from 'next-themes' // Your themeing variables const GlobalStyle = createGlobalStyle` :root { --fg: #000; --bg: #fff; } [data-theme="dark"] { --fg: #fff; --bg: #000; } ` function MyApp({ Component, pageProps }) { return ( <> ) } ``` -------------------------------- ### Disable System Preference Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Example of disabling the system preference and setting a default theme. ```tsx {children} ``` -------------------------------- ### Mismatched Configuration Example (WRONG) Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Illustrates incorrect usage where ThemeScript and ThemeProvider have different attributes. ```tsx // ❌ Script expects 'data-theme' but React uses 'data-mode' {children} ``` -------------------------------- ### Using with custom themes Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of using ThemeProvider with custom themes defined. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Validate theme before setting Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/README.md This example shows how to validate a new theme against the available themes before attempting to set it. ```typescript const { themes, setTheme } = useTheme() function changeTheme(newTheme) { if (themes.includes(newTheme)) { setTheme(newTheme) } } ``` -------------------------------- ### Customizing DOM attribute value Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example of how to customize the DOM attribute value for a theme. ```jsx ``` -------------------------------- ### Theme with CSP Nonce Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/recipes.md Secure setup with Content Security Policy by providing a nonce. ```typescript // This should be in a server component import { ThemeProvider } from 'next-themes' import { headers } from 'next/headers' export default function RootLayout({ children }) { // Get nonce from request headers const headersList = headers() const nonce = headersList.get('x-nonce') || '' return ( {children} ) } // middleware.ts - Generate and set nonce import { NextRequest, NextResponse } from 'next/server' import { crypto } from 'node:crypto' export function middleware(request: NextRequest) { const nonce = crypto.randomUUID() const response = NextResponse.next() response.headers.set('x-nonce', nonce) return response } ``` -------------------------------- ### Use Theme Hook Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Shows how to access the current theme value within a component using the useTheme hook. ```typescript const { theme } = useTheme() // theme is "dark", not "dark-mode" localStorage.getItem('theme') // "dark", not "dark-mode" document.documentElement.getAttribute('data-theme') // "dark-mode", not "dark" ``` -------------------------------- ### Using resolvedTheme for Conditional Styling Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md An example demonstrating how to use the 'resolvedTheme' hook from useTheme to apply conditional styles based on the resolved theme. ```jsx const { resolvedTheme } = useTheme()
``` -------------------------------- ### Multiple Theme Queries Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/use-theme.md Demonstrates calling the useTheme hook multiple times within the same component. It highlights that subsequent calls return the same context value. ```typescript const firstCall = useTheme() const secondCall = useTheme() // Both are identical ``` -------------------------------- ### Handling System Theme Not Available Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of how to conditionally render the 'system' option based on availability. ```tsx function ThemeSwitcher() { const { theme, setTheme, systemTheme, enableSystem } = useTheme() // Check if system theme is available const isSystemAvailable = systemTheme !== undefined && enableSystem return ( ) } ``` -------------------------------- ### With Cloudflare Rocket Loader Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of configuring ThemeProvider to work with Cloudflare Rocket Loader. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Using both class and data-theme attributes Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of using both 'class' and 'data-theme' attributes for theme switching. ```tsx // Updates both: ``` -------------------------------- ### Using attribute="class" Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of using the 'class' attribute for theme switching. ```tsx // Updates: ``` -------------------------------- ### Using attribute="data-theme" Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of using the 'data-theme' attribute for theme switching. ```tsx // Updates: ``` -------------------------------- ### Basic theme switching Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/use-theme.md Demonstrates how to use the useTheme hook to get the current theme and switch between 'light' and 'dark' themes. ```typescript import { useTheme } from 'next-themes' export function ThemeSwitcher() { const { theme, setTheme } = useTheme() return (
Current theme: {theme}
) } ``` -------------------------------- ### Forcing a theme on a specific page Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of forcing a specific theme on a particular page. ```typescript // app/marketing/page.tsx import { ThemeProvider } from 'next-themes' const Page = ({ children }) => { return ( {children} ) } export default Page ``` -------------------------------- ### Defer theme-dependent UI until mounted Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/README.md This example shows how to defer rendering theme-dependent UI until the component has mounted to avoid hydration mismatches. ```typescript const [mounted, setMounted] = useState(false) const { theme } = useTheme() useEffect(() => { setMounted(true) }, []) if (!mounted) return null // Now safe to render theme-dependent UI ``` -------------------------------- ### Hiding content based on theme using CSS attributes Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md This example demonstrates how to use CSS to conditionally show or hide content based on the current theme. It involves rendering both versions of the UI and using data attributes to control their visibility, thus avoiding hydration mismatches. ```jsx function ThemedImage() { return ( <> {/* When the theme is dark, hide this div */}
{/* When the theme is light, hide this div */}
) } export default ThemedImage ``` ```css [data-theme='dark'] [data-hide-on-theme='dark'], [data-theme='light'] [data-hide-on-theme='light'] { display: none; } ``` -------------------------------- ### Lazy loading ThemeSwitch component with next/dynamic Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md This example demonstrates how to prevent hydration mismatches by lazy loading the ThemeSwitch component on the client side using next/dynamic, disabling server-side rendering for this component. ```js import dynamic from 'next/dynamic' const ThemeSwitch = dynamic(() => import('./ThemeSwitch'), { ssr: false }) const ThemePage = () => { return (
) } export default ThemePage ``` -------------------------------- ### Manual usage with CSP nonce Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-script.md Example of manually injecting ThemeScript with a CSP nonce in a custom layout. ```tsx import { ThemeScript } from 'next-themes' export default function Layout({ children }) { return ( {children} ) } ``` -------------------------------- ### Mapping theme names to attribute values Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of mapping theme names to specific attribute values. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Manual usage with Cloudflare Rocket Loader Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-script.md Example of manually injecting ThemeScript and disabling Cloudflare Rocket Loader. ```tsx import { ThemeScript } from 'next-themes' export default function Layout({ children }) { return ( {children} ) } ``` -------------------------------- ### Cloudflare Rocket Loader Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-script.md Example of how to disable Cloudflare Rocket Loader for the ThemeScript component. ```tsx ``` -------------------------------- ### Manual Usage with Custom Attributes Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-script.md Example of manually using ThemeScript with custom attributes like 'class' and 'data-mode', along with storage key, default theme, and theme mappings. ```tsx import { ThemeScript } from 'next-themes' export default function Layout({ children }) { return ( {children} ) } ``` -------------------------------- ### SSR Hydration Mismatch - Incorrect Example Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of a component that causes hydration mismatch because it renders differently on server vs client. ```tsx function ThemeSwitch() { const { theme, setTheme } = useTheme() // ❌ This renders differently on server vs client! return ( ) } ``` -------------------------------- ### TypeScript Import Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-overview.md How to import ThemeProvider, useTheme, and type definitions using TypeScript. ```typescript import { ThemeProvider, useTheme } from 'next-themes' import type { UseThemeProps, ThemeProviderProps, Attribute } from 'next-themes' ``` -------------------------------- ### ES Modules Import Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-overview.md How to import ThemeProvider and useTheme using ES Modules. ```javascript import { ThemeProvider, useTheme } from 'next-themes' ``` -------------------------------- ### ThemeProvider with Custom Attribute Source: https://github.com/pacocoursey/next-themes/blob/main/README.md Example of setting the 'data-mode' attribute for ThemeProvider in Next.js. ```typescript // pages/_app.tsx ``` -------------------------------- ### ThemeProvider Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md All your theme configuration is passed to ThemeProvider. ```jsx ``` ```jsx ``` ```jsx ``` -------------------------------- ### Force page to a theme - _app component Source: https://github.com/pacocoursey/next-themes/blob/main/README.md In your `_app`, read the variable and pass it to ThemeProvider: ```jsx function MyApp({ Component, pageProps }) { return ( ) } ``` -------------------------------- ### CommonJS Import Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-overview.md How to import ThemeProvider and useTheme using CommonJS. ```javascript const { ThemeProvider, useTheme } = require('next-themes') ``` -------------------------------- ### Using useTheme hook and checking localStorage/DOM Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Demonstrates the values returned by useTheme, localStorage, and the DOM attribute after applying a custom value. ```js const { theme } = useTheme() // => "pink" localStorage.getItem('theme') // => "pink" document.documentElement.getAttribute('data-theme') // => "my-pink-theme" ``` -------------------------------- ### Disable transitions on theme change Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of disabling transitions when the theme changes. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Use System preference by default Source: https://github.com/pacocoursey/next-themes/blob/main/README.md For versions above v0.0.12, the `defaultTheme` is automatically set to "system", so to use System preference you can simply use: ```jsx ``` -------------------------------- ### Automatic usage (via ThemeProvider) Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-script.md Example of how ThemeProvider automatically includes ThemeScript. ```tsx import { ThemeProvider } from 'next-themes' export default function Layout({ children }) { return ( {children} ) } ``` -------------------------------- ### Multiple Custom Themes Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Configuring ThemeProvider to support multiple custom themes. ```tsx {children} ``` -------------------------------- ### Safe ThemeSwitch component using useEffect for client-side mounting Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md This code sample shows a safe way to implement a theme switcher by using the useEffect hook to ensure that the UI is only rendered after the component has mounted on the client, thus avoiding hydration mismatches. ```jsx import { useState, useEffect } from 'react' import { useTheme } from 'next-themes' const ThemeSwitch = () => { const [mounted, setMounted] = useState(false) const { theme, setTheme } = useTheme() // useEffect only runs on the client, so now we can safely show the UI useEffect(() => { setMounted(true) }, []) if (!mounted) { return null } return ( ) } export default ThemeSwitch ``` -------------------------------- ### Detecting and Handling Forced Theme Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of how to disable theme switching when a theme is forced. ```tsx function ThemeSwitcher() { const { theme, setTheme, forcedTheme } = useTheme() // If theme is forced, disable switching const isDisabled = forcedTheme !== undefined if (isDisabled) { return

Theme is fixed to {forcedTheme}

} return ( ) } ``` -------------------------------- ### localStorage Unavailable - saveToLS function Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of how the saveToLS function handles localStorage unavailability. ```typescript const saveToLS = (storageKey: string, value: string) => { try { localStorage.setItem(storageKey, value) } catch (e) { // Silently ignored - theme changes work but aren't persisted } } ``` -------------------------------- ### Check if theme is forced Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/README.md This example demonstrates how to check if a theme is currently forced, which can happen in certain SSR scenarios. ```typescript const { forcedTheme } = useTheme() if (forcedTheme) { return

Theme is locked to {forcedTheme}

} ``` -------------------------------- ### Preventing Invalid Theme Names Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of how to ensure only valid themes from the 'themes' list are set. ```tsx function ThemeSwitcher() { const { theme, setTheme, themes } = useTheme() // Only allow setting to themes in the themes list const handleChangeTheme = (newTheme: string) => { if (themes.includes(newTheme)) { setTheme(newTheme) } } return ( ) } ``` -------------------------------- ### localStorage Unavailable - Handling in a React Component Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of how to check for private browsing and warn the user. ```tsx function ThemeSwitcher() { const { theme, setTheme } = useTheme() const [isPrivate, setIsPrivate] = useState(false) useEffect(() => { try { const test = '__test' localStorage.setItem(test, test) localStorage.removeItem(test) } catch { setIsPrivate(true) } }, []) if (isPrivate) { return

Theme preferences won't persist in private browsing

} return ( ) } ``` -------------------------------- ### ThemeProvider attribute configuration for TailwindCSS Source: https://github.com/pacocoursey/next-themes/blob/main/next-themes/README.md Example of configuring the ThemeProvider in `pages/_app.tsx` to use the 'class' attribute, which is necessary when integrating with TailwindCSS for dark mode. ```tsx ``` -------------------------------- ### Fixing CSP Blocking Script Tag Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/error-handling.md Example of providing a nonce to the ThemeProvider and setting the CSP header. ```tsx // Server generates nonce const nonce = crypto.randomUUID() // Pass nonce to provider {children} // Set CSP header response.headers.set( 'Content-Security-Policy', `script-src 'nonce-${nonce}'` ) ``` -------------------------------- ### Enable system preference Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/configuration.md Enables system preference detection using the `prefers-color-scheme` media query. The app will automatically switch between dark and light themes based on the OS/browser setting. Users can still manually override the system preference. ```tsx // Enable system preference (default) {/* System preference is used */} // Disable system preference {/* Only manual theme selection */} // Enable system but default to light {/* System preference available but light is default */} ``` -------------------------------- ### Use resolved theme for styling Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/README.md This example illustrates how to use the resolved theme (the actual theme applied) for conditional styling. ```typescript const { resolvedTheme } = useTheme() const isDark = resolvedTheme === 'dark' const color = isDark ? '#fff' : '#000' ``` -------------------------------- ### Disable system preference detection Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of disabling system preference detection and setting a default theme. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ``` -------------------------------- ### Ignore System preference Source: https://github.com/pacocoursey/next-themes/blob/main/README.md If you don't want a System theme, disable it via `enableSystem`: ```jsx ``` -------------------------------- ### Using class attribute with Tailwind CSS Source: https://github.com/pacocoursey/next-themes/blob/main/_autodocs/api-reference/theme-provider.md Example of using ThemeProvider with the 'class' attribute for Tailwind CSS. ```typescript import { ThemeProvider } from 'next-themes' export default function RootLayout({ children }) { return ( {children} ) } ```