bash Copy code
# Install dependencies
npm install @emotion/react @emotion/styled
# No dev deps needed for TypeScript, as Next.js includes types
1. Define your theme (lib/themes.ts)
ts Copy code
export type ThemeMode = 'light' | 'dark'
export interface AppTheme {
palette: {
mode: ThemeMode
primary: {
main: string
contrastText: string
}
background: {
default: string
paper: string
}
text: {
primary: string
}
}
}
export const getAppTheme = (mode: ThemeMode): AppTheme => ({
palette: {
mode,
primary: {
main: '#1976d2',
contrastText: '#ffffff',
},
background: mode === 'light'
? {
default: '#f5f5f5',
paper: '#ffffff',
}
: {
default: '#121212',
paper: '#1e1e1e',
},
text: mode === 'light'
? {
primary: 'rgba(0, 0, 0, 0.87)',
}
: {
primary: '#ffffff',
},
},
})
2. Create the theme provider with toggle (lib/ThemeProvider.tsx)
tsx Copy code
'use client'
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { ThemeProvider as EmotionThemeProvider } from '@emotion/react'
import { getAppTheme, ThemeMode, AppTheme } from './themes'
interface ThemeContextValue {
theme: ThemeMode
toggleTheme: () => void
}
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined)
export function WebThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<ThemeMode>('light')
// Load theme from localStorage on mount
useEffect(() => {
const stored = localStorage.getItem('theme') as ThemeMode | null
const initialTheme = stored ?? 'light'
setTheme(initialTheme)
}, [])
// Persist theme to localStorage and update data attribute for potential CSS vars
useEffect(() => {
localStorage.setItem('theme', theme)
if (typeof document !== 'undefined') {
document.documentElement.setAttribute('data-theme', theme)
}
}, [theme])
const toggleTheme = () => {
setTheme((prev) => (prev === 'light' ? 'dark' : 'light'))
}
const appTheme: AppTheme = getAppTheme(theme)
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<EmotionThemeProvider theme={appTheme}>{children}</EmotionThemeProvider>
</ThemeContext.Provider>
)
}
export const useTheme = (): ThemeContextValue => {
const context = useContext(ThemeContext)
if (context === undefined) {
throw new Error('`useTheme` must be used within `WebThemeProvider`')
}
return context
}
3. Create Emotion cache registry for SSR (lib/Registry.tsx)
This handles server-side rendering (SSR) for Emotion in Next.js App Router.
tsx Copy code
'use client'
import React from 'react'
import createCache from '@emotion/cache'
import { CacheProvider } from '@emotion/react'
import { useServerInsertedHTML } from 'next/navigation'
export default function EmotionRegistry({ children }: { children: React.ReactNode }) {
const [{ cache, flush }] = React.useState(() => {
const cache = createCache({ key: 'emotion', prepend: true })
cache.compat = true
const prevInsert = (cache.insert as any).bind(cache)
let inserted: string[] = []
;(cache.insert as any) = (...args: any[]) => {
const serialized = args[1]
if (!cache.inserted[serialized.name]) {
inserted.push(serialized.name)
}
return prevInsert(...args)
}
const flush = () => {
const prevInserted = inserted
inserted = []
return prevInserted
}
return { cache, flush }
})
useServerInsertedHTML(() => {
const names = flush()
if (names.length === 0) return null
let styles = ''
for (const name of names) {
styles += cache.inserted[name]
}
return (
<style
key={cache.key}
data-emotion={`${cache.key} ${names.join(' ')}`}
dangerouslySetInnerHTML={{
__html: styles,
}}
/>
)
})
return <CacheProvider value={cache}>{children}</CacheProvider>
}
4. Update your root layout (app/layout.tsx)
tsx Copy code
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
import EmotionRegistry from '@/lib/Registry'
import { WebThemeProvider } from '@/lib/ThemeProvider'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'My Next.js App',
description: 'CSS-in-JS with theming',
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html suppressHydrationWarning lang="en">
<body className={inter.className}>
<EmotionRegistry>
<WebThemeProvider>{children}</WebThemeProvider>
</EmotionRegistry>
</body>
</html>
)
}
5. Example styled component (components/ThemedButton.tsx)
tsx Copy code
'use client'
import styled from '@emotion/styled'
const StyledButton = styled.button`
background-color: ${({ theme }) => theme.palette.primary.main};
color: ${({ theme }) => theme.palette.primary.contrastText};
border: none;
padding: 12px 24px;
border-radius: 6px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.2s ease;
&:hover {
background-color: ${({ theme }) =>
theme.palette.mode === 'light'
? 'rgba(25, 118, 210, 0.8)'
: 'rgba(25, 118, 210, 1.2)'};
}
`
interface ThemedButtonProps {
children: React.ReactNode
onClick?: () => void
}
export default function ThemedButton({ children, onClick }: ThemedButtonProps) {
return <StyledButton onClick={onClick}>{children}</StyledButton>
}
6. Example usage in a page (app/page.tsx)
tsx Copy code
'use client'
import { useTheme } from '@/lib/ThemeProvider'
import ThemedButton from '@/components/ThemedButton'
export default function Home() {
const { theme, toggleTheme } = useTheme()
return (
<main
style={{
padding: '2rem',
backgroundColor: 'var(--bg-default)', // Optional: pairs with data-theme
minHeight: '100vh',
}}
>
<h1>CSS-in-JS Theming Demo</h1>
<p>Current theme: <strong>{theme}</strong></p>
<ThemedButton onClick={toggleTheme}>Toggle Theme</ThemedButton>
</main>
)
}
Key Features
Theming : Light/dark modes with persistence via localStorage.
SSR-friendly : Emotion cache ensures styles are rendered on the server.
Toggle : Use useTheme() hook anywhere inside providers.
Extensible : Add more theme properties or modes in getAppTheme.
Performance : Zero-runtime theme switching after hydration.
TypeScript : Fully typed.
Run npm run dev and toggle the theme—styles update instantly with proper SSR hydration! Extend AppTheme for more customization (e.g., spacing, typography).