- Create ThemeSessionBridge.tsx: useEffect compares session.user.theme to
next-themes value; calls setTheme(serverTheme) on mismatch; validates
against 3-string allowlist ('light'|'dark'|'system'); renders null
- Mount <ThemeSessionBridge /> as first child of <AuthProvider> in app/layout.tsx
- Modify ThemeToggle: writeTheme() calls setTheme() then fire-and-forget
PUT /api/me/theme; silent catch for network errors (best-effort desktop UX)
38 lines
1,016 B
TypeScript
38 lines
1,016 B
TypeScript
'use client';
|
|
|
|
/**
|
|
* ThemeSessionBridge (THEME-03 / D-16, D-17).
|
|
*
|
|
* On session load and after sign-in, compares session.user.theme to the
|
|
* next-themes useTheme() value and calls setTheme(session.user.theme) if
|
|
* different. Server is canonical; this is the bridge that enforces it.
|
|
*
|
|
* Renders nothing.
|
|
*/
|
|
|
|
import { useEffect } from 'react';
|
|
import { useTheme } from 'next-themes';
|
|
import { useSession } from '@/lib/auth-client';
|
|
|
|
type SessionUserWithTheme = { theme?: 'light' | 'dark' | 'system' | string };
|
|
|
|
export function ThemeSessionBridge() {
|
|
const { data: session } = useSession();
|
|
const { theme, setTheme } = useTheme();
|
|
|
|
useEffect(() => {
|
|
if (!session?.user) return;
|
|
const serverTheme = (session.user as SessionUserWithTheme).theme;
|
|
if (
|
|
serverTheme === 'light' ||
|
|
serverTheme === 'dark' ||
|
|
serverTheme === 'system'
|
|
) {
|
|
if (serverTheme !== theme) {
|
|
setTheme(serverTheme);
|
|
}
|
|
}
|
|
}, [session?.user, theme, setTheme]);
|
|
|
|
return null;
|
|
}
|