Repository navigation
fix : preserve dark theme on locale switch and fix React 19 script wa… - #99
Conversation
📝 WalkthroughWalkthroughThe ChangesDark Mode Route Awareness and Hydration Fix
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/app/`[lang]/layout.tsx:
- Around line 40-41: The conditional logic for the script `type` attribute in
the layout.tsx Server Component evaluates only on the server during rendering,
so the `typeof window === "undefined"` check never switches to `text/plain` on
the client as intended. To fix this, convert the layout.tsx component to a
Client Component by adding the `use client` directive at the top of the file,
which will cause the script `type` attribute conditional to re-evaluate on the
client side where the window object is available and the type can properly
switch between `text/javascript` and `text/plain` for the React 19 hydration
warning mitigation.
In `@src/lib/use-theme.ts`:
- Around line 21-28: The theme resolution logic in the try block does not
properly handle storage failures. When localStorage.getItem("theme") throws an
error in restricted storage contexts, the entire theme determination is skipped,
including the matchMedia fallback. Restructure the logic by wrapping the
localStorage.getItem call in its own try-catch, and ensure that when
localStorage access fails, the code still falls back to using
window.matchMedia("(prefers-color-scheme: dark)").matches to determine the
theme. This way the document.documentElement.classList.toggle("dark", d) call
will always execute with a valid theme decision regardless of whether storage is
accessible.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 9782d1d9-ba82-4b4b-a2cc-1c07ff423177
📒 Files selected for processing (2)
src/app/[lang]/layout.tsxsrc/lib/use-theme.ts
| type={typeof window === "undefined" ? "text/javascript" : "text/plain"} | ||
| suppressHydrationWarning |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In Next.js App Router (v16), are app/**/layout.tsxfiles Server Components by default, and doestypeof window in those files evaluate server-side only (making it unsuitable for client-only script-type toggling)?
💡 Result:
In Next.js 16, app/layout.tsx files (and all other components within the app directory) are React Server Components by default [1][2][3]. Because they are Server Components, they execute on the server during the initial request [1][2][4]. Regarding your question about typeof window: 1. Server-Side Evaluation: When a layout.tsx file is a Server Component, code within the top-level scope (including typeof window checks) runs on the server [2][5]. Consequently, typeof window will evaluate to "undefined" on the server [5][6]. 2. Suitability for Client-Only Script Toggling: Using typeof window inside a Server Component layout is not a recommended or reliable way to perform client-side script toggling [7]. Because Server Components must remain deterministic during server-side rendering, attempting to conditionally render content based on the environment using typeof window can lead to hydration mismatches, where the server-rendered HTML does not match the client-side initial render [7]. Best Practice: If you need to execute code only in the browser or toggle UI based on client-side availability, you should: - Move that logic into a separate Client Component (marked with the 'use client' directive) [2][8]. - Utilize React hooks like useEffect, which only run on the client after hydration, to handle browser-specific APIs or script toggling [7]. - Alternatively, if you must keep the layout as a Server Component, you can import a Client Component to manage the client-side interactivity, ensuring that the environment-specific logic is encapsulated where it can safely access browser globals [8].
Citations:
- 1: https://getcraftly.dev/blog/nextjs-16-app-router-guide
- 2: https://hpweb.dev/learning/nextjs/project-setup-app-router
- 3: https://jstechlog.com/en/posts/nextjs-app-router-guide/
- 4: https://stacknotice.com/blog/nextjs-app-router-complete-guide-2026
- 5: window is not defined vercel/next.js#47028
- 6: https://github.com/vercel/next.js/blob/canary/packages/next/src/client/components/layout-router.tsx
- 7: https://nextjs.org/docs/messages/react-hydration-error
- 8: Best Practice: Should 'use client' be avoided in layout.tsx files? vercel/next.js#76015
type does not actually switch to text/plain because the decision is made server-side.
Since layout.tsx is a Server Component by default in Next.js App Router, the typeof window === "undefined" expression evaluates on the server, not the client. This means the script type attribute is set once during server rendering and remains fixed in the emitted HTML—the client never re-evaluates this condition. The React 19 warning/double-execution mitigation described in the PR is therefore not achieved.
🧰 Tools
🪛 ast-grep (0.43.0)
[warning] 41-41: Usage of dangerouslySetInnerHTML detected. This bypasses React's built-in XSS protection. Always sanitize HTML content using libraries like DOMPurify before injecting it into the DOM to prevent XSS attacks.
Context: dangerouslySetInnerHTML
Note: [CWE-79] Improper Neutralization of Input During Web Page Generation
(react-unsafe-html-injection)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/app/`[lang]/layout.tsx around lines 40 - 41, The conditional logic for
the script `type` attribute in the layout.tsx Server Component evaluates only on
the server during rendering, so the `typeof window === "undefined"` check never
switches to `text/plain` on the client as intended. To fix this, convert the
layout.tsx component to a Client Component by adding the `use client` directive
at the top of the file, which will cause the script `type` attribute conditional
to re-evaluate on the client side where the window object is available and the
type can properly switch between `text/javascript` and `text/plain` for the
React 19 hydration warning mitigation.
| const theme = localStorage.getItem("theme"); | ||
| const d = theme | ||
| ? theme === "dark" | ||
| : window.matchMedia("(prefers-color-scheme: dark)").matches; | ||
| document.documentElement.classList.toggle("dark", d); | ||
| } catch (e) { | ||
| console.error(e); | ||
| } |
There was a problem hiding this comment.
Harden theme resolution so fallback still works when storage access fails.
Right now, a storage error skips the matchMedia fallback entirely, and any non-empty unexpected value is forced to light. This can leave the route-transition fix ineffective in restricted storage contexts.
Suggested patch
useEffect(() => {
- try {
- const theme = localStorage.getItem("theme");
- const d = theme
- ? theme === "dark"
- : window.matchMedia("(prefers-color-scheme: dark)").matches;
- document.documentElement.classList.toggle("dark", d);
- } catch (e) {
- console.error(e);
- }
+ let d = window.matchMedia("(prefers-color-scheme: dark)").matches;
+ try {
+ const theme = localStorage.getItem("theme");
+ if (theme === "dark") d = true;
+ else if (theme === "light") d = false;
+ } catch (e) {
+ console.error(e);
+ }
+ document.documentElement.classList.toggle("dark", d);
}, [pathname]);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const theme = localStorage.getItem("theme"); | |
| const d = theme | |
| ? theme === "dark" | |
| : window.matchMedia("(prefers-color-scheme: dark)").matches; | |
| document.documentElement.classList.toggle("dark", d); | |
| } catch (e) { | |
| console.error(e); | |
| } | |
| useEffect(() => { | |
| let d = window.matchMedia("(prefers-color-scheme: dark)").matches; | |
| try { | |
| const theme = localStorage.getItem("theme"); | |
| if (theme === "dark") d = true; | |
| else if (theme === "light") d = false; | |
| } catch (e) { | |
| console.error(e); | |
| } | |
| document.documentElement.classList.toggle("dark", d); | |
| }, [pathname]); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@src/lib/use-theme.ts` around lines 21 - 28, The theme resolution logic in the
try block does not properly handle storage failures. When
localStorage.getItem("theme") throws an error in restricted storage contexts,
the entire theme determination is skipped, including the matchMedia fallback.
Restructure the logic by wrapping the localStorage.getItem call in its own
try-catch, and ensure that when localStorage access fails, the code still falls
back to using window.matchMedia("(prefers-color-scheme: dark)").matches to
determine the theme. This way the
document.documentElement.classList.toggle("dark", d) call will always execute
with a valid theme decision regardless of whether storage is accessible.
Pull Request: Fix Theme Reset on Locale Switch & React 19 Layout Warning
Description
This PR resolves Issue #95 ("Theme preference resets to light when switching language").
It addresses the issue of theme state loss during client-side route transitions (when changing the locale dynamic path parameter
[lang]) and fixes the React 19 raw script tag console warning thrown during client navigation.Key Changes
1. Theme Persistence on Locale Transitions (
src/lib/use-theme.ts)usePathname-linkeduseEffectin theuseIsDarktheme state tracker hook./ento/es), the effect reads their theme choice (localStorage.theme) or system default and restores the"dark"class todocument.documentElement, preventing React's router reconciler from resetting the layout back to light mode.2. React 19 Script Tag Warning Resolution (
src/app/[lang]/layout.tsx)text/javascriptand runs synchronously before page load to apply the theme instantly.text/plain, meaning React 19 recognizes it as plain text rather than an active script, eliminating the console warning when switching languages.Verification & Testing Results
pnpm testcompleted successfully with all 43/43 tests passing.pnpm buildfinished with zero errors, verifying correct compilation for all static locale pages under Next.js 16/Turbopack.Summary by CodeRabbit