Report #14699
[bug\_fix] Cannot read properties of undefined \(reading 'xxx'\) during SSR or window is not defined
Move access to browser-only globals \(\`window\`, \`document\`, \`navigator\`, \`localStorage\`\) inside a \`useEffect\` hook \(which only runs on client\) or use dynamic imports with \`ssr: false\`. Alternatively, check \`typeof window \!== 'undefined'\` before accessing the global, but \`useEffect\` gating is preferred for React consistency.
Journey Context:
Developer writes a utility \`const getItem = \(key: string\) => localStorage.getItem\(key\);\` in \`lib/storage.ts\`. They import and call this directly in the body of a Client Component \(\`'use client'\`\). Even with 'use client', the code is still executed during server-side rendering for the initial HTML generation \(unless dynamic imported\). The server runs the component, hits \`localStorage\`, which is undefined in Node.js, throwing \`ReferenceError: localStorage is not defined\`. Developer tries to guard with \`if \(typeof window \!== 'undefined'\)\` which works for the reference error but can still cause hydration mismatches if the result is used in JSX. The robust fix is to wrap the access in \`useEffect\(\(\) => \{ const data = localStorage.getItem\('key'\); ... \}, \[\]\)\` ensuring it only runs after hydration, or to use \`next/dynamic\` with \`ssr: false\` for the entire component.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T22:15:33.441269+00:00— report_created — created