Recommended Free Tools
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Browser-only code fails in server rendering for two different reasons: the server may throw because globals such as window or localStorage do not exist, or hydration may warn because the server HTML and the browser’s first render produce different output. The fixes are related but not interchangeable.
Keep the first render deterministic, move browser reads into a client-only lifecycle step when a server fallback is acceptable, or isolate a genuinely browser-dependent widget behind a no-SSR boundary. If a value must shape the initial HTML, provide it to the server through a request-readable input instead of discovering it only in the browser.
Two failures that look alike but need different fixes
When an application is moved to server-side rendering (SSR), developers often see one of two messages: window is not defined or a hydration warning saying that server-rendered text does not match the client. Both involve browser-dependent code, but they occur at different points in the rendering lifecycle.
Server exception: a browser global is missing
SSR executes component code in a server runtime, not inside a browser tab. That runtime normally has no window, document, DOM, navigator, or localStorage. A direct read during rendering therefore throws before HTML can be produced:
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
const theme = window.localStorage.getItem('theme');
The same problem can be hidden in an imported dependency. A package may touch window while its module is initialized, so the exception appears when your component imports it even if your own render function never mentions a browser global.
Hydration mismatch: server and first client output differ
Hydration is the browser’s process of attaching React behavior to HTML that the server already emitted. React expects the browser’s initial render to produce the same tree and text as the server output. If the server renders “Sign in” but the browser immediately reads a stored token and renders “Account,” the DOM and React tree disagree.
A guard such as typeof window !== 'undefined' can prevent a reference error while still creating this mismatch:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →function Greeting() {
const name = typeof window !== 'undefined'
? window.localStorage.getItem('name')
: null;
return <span>{name ? `Hello, ${name}` : 'Hello, guest'}</span>;
}
The server takes the guest branch. The first browser render takes the stored-name branch. The code does not crash, but the initial output is not equivalent.
Why a client component can still run during SSR
In Next.js, marking a module with 'use client' defines a client component boundary for features such as state, event handlers, and effects. It does not automatically mean that the component’s first render happens only in a browser. Client Components can be prerendered on the server and then hydrated in the browser.
That distinction explains why this code is unsafe in a Client Component:
'use client';
export default function Preferences() {
const compact = window.localStorage.getItem('compact') === '1';
return <div className={compact ? 'compact' : 'comfortable'}>...</div>;
}
The component is eligible to use browser APIs after hydration, but its render function still has to survive the server pass. Treat 'use client' as a capability boundary, not as a promise that render-time code is browser-only.
Free tools Windows power users keep installed
One-click scans. No signup required.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
How to diagnose the failure before changing code
Use a deliberate sequence rather than adding guards at random. The objective is to identify whether the problem is an exception, a mismatch, or an unrelated source of nondeterministic HTML.
- Classify the symptom. A stack trace containing
window is not defined,document is not defined, or a storage error indicates code executed in the server render or during module initialization. A message about text or attributes differing during hydration means the server completed, but the first client output disagreed. - Trace the complete render path. Search the component and every dependency it imports for
window,document,localStorage,sessionStorage, media-query APIs, size measurements, geolocation, and other browser-only features. Check top-level module code as well as functions; an access outside a component can fail as soon as the module is loaded. - Capture the server HTML and first client state. Compare the actual response HTML with what the component renders before any effect runs. Look for different text, class names, element counts, checked states, and attributes. Do not compare the page after effects have completed; that later state is expected to differ when browser data is loaded asynchronously.
- Check common non-browser causes. Next.js also identifies invalid HTML nesting, time-dependent values such as
Date(), browser extensions that mutate the page, CSS-in-JS configuration errors, and an edge or CDN layer that rewrites the response as possible hydration causes. - Inspect the boundary. Determine whether the component is a Server Component, a Client Component that is still prerendered, or a separately loaded browser-only module. The correct remedy depends on that boundary and on the framework version.
Fix 1: render a stable fallback, then read the browser in an effect
Use this pattern when the server can show useful placeholder or default content and the browser-specific value can arrive after hydration. Effects run only on the client, so the server and the initial browser render share the same state.
'use client';
import { useEffect, useState } from 'react';
export default function ThemeLabel() {
const [theme, setTheme] = useState('light');
useEffect(() => {
const saved = window.localStorage.getItem('theme');
if (saved === 'light' || saved === 'dark') {
setTheme(saved);
}
}, []);
return <p>Theme: {theme}</p>;
}
The server emits Theme: light, and the first client render emits the same text. After hydration, the effect may update the label to the stored value. That update is a normal state transition, not a hydration mismatch.
Choosing a good initial value
The fallback should be valid for every request and should not imply that a browser lookup already succeeded. Use a neutral label such as “Loading preferences,” a deterministic default, or a skeleton that has the same structure and dimensions on both renders. If the fallback changes layout substantially, reserve space so the post-effect update does not cause a jarring shift.
Handling storage failures
Storage can be disabled, unavailable in private browsing modes, blocked by policy, or contain malformed data. Keep the read inside a try/catch and validate the value before updating state:
useEffect(() => {
try {
const raw = window.localStorage.getItem('settings');
if (!raw) return;
const parsed = JSON.parse(raw);
if (parsed && (parsed.mode === 'light' || parsed.mode === 'dark')) {
setMode(parsed.mode);
}
} catch {
// Keep the deterministic server default.
}
}, []);
Do not initialize state by calling localStorage in the useState initializer. Initializers run during the server render too. Reading in an effect is the part that makes this pattern safe.
When the delayed update is not acceptable
An effect deliberately postpones browser state. Users may briefly see the fallback, and search engines or users who never run JavaScript will see only the server version. If the preference must be reflected in the first HTML—for example, a consent choice that changes which controls are present—use a server-readable input instead of accepting a delayed update.
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Fix 2: isolate a truly browser-only component and disable SSR for it
Some widgets cannot produce meaningful server output. Examples include a canvas editor that requires a DOM, a map library that measures the viewport during initialization, or a third-party component that accesses window as soon as it is imported. In Next.js, a narrow dynamic-import boundary can prevent that component from being prerendered:
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware match'use client';
import dynamic from 'next/dynamic';
const BrowserWidget = dynamic(() => import('./BrowserWidget'), {
ssr: false,
loading: () => <p>Loading interactive widget…</p>
});
export default function WidgetSection() {
return <BrowserWidget />;
}
ssr: false applies to that dynamically imported component. The server sends the surrounding page and the loading UI, while the widget is loaded and rendered in the browser. This avoids server execution of the problematic code but gives up server-rendered output for the isolated widget.
Keep the boundary as small as possible
Do not disable SSR for an entire page merely because one chart or editor needs the browser. A broad no-SSR boundary removes useful HTML, delays more content, and can hurt accessibility and perceived performance. Wrap only the component that cannot render safely, and keep headings, explanatory text, and controls that do not need the DOM server-rendered.
Make the imported module safe at its boundary
Even with a client-only import, avoid exporting server-used helpers from the same module if those helpers initialize browser globals at top level. Separate browser initialization from data formatting and other universal code. If a library offers a server-safe entry point, use that entry point for code that still participates in SSR.
Fix 3: provide the initial value to the server
When a value must determine the initial HTML, the server and browser need a shared input. Depending on the application, that input can be a request cookie, a URL parameter, authenticated session data, or another server-readable request attribute. Read it in the server-side portion of the framework and pass the resulting value into the component as a prop.
// Server-rendered component
export default async function AccountPage() {
const preference = await readPreferenceFromRequest();
return <AccountShell initialPreference={preference} />;
}
'use client';
export default function AccountShell({ initialPreference }) {
const [preference, setPreference] = useState(initialPreference);
// Browser-only synchronization can still happen in an effect.
return <section data-preference={preference}>...</section>;
}
The important property is not the specific storage mechanism; it is that both renders receive the same initial value. Choose inputs with appropriate security characteristics. A cookie sent with a request may be visible to the server, while a secret that must never reach the browser should not be passed as a client prop. Validate and normalize request data before using it to shape markup.
Why a browser-only preference cannot be read by the server
localStorage belongs to a particular browser origin and is not included in an HTTP request. The server therefore cannot inspect it during a normal request unless the application deliberately copies the preference into a request-readable channel. If no such channel exists, the honest choices are a deterministic fallback followed by an effect, or a browser-only component.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Fix 4: use hydration-warning suppression only as a narrow escape hatch
Next.js documents suppressHydrationWarning for unavoidable differences such as a timestamp that is intentionally different on the server and client. It suppresses a warning one level deep; it does not make the markup equivalent, and React will not patch mismatched text content in that suppressed case.
<time suppressHydrationWarning>{formattedTime}</time>
Use this only when all of the following are true:
- The difference is intentional and limited to the element being marked.
- You understand which side’s text will remain in the DOM until your own code updates it.
- There is no practical way to provide the same initial value to both renders.
Do not use suppression to hide a storage read, a changing authentication state, or a large subtree with divergent structure. In those cases, fix the rendering boundary or the data flow. Suppression can make debugging harder while leaving stale or incorrect content visible.
Conditional rendering with localStorage without a mismatch
A common question is how to conditionally render a component based on localStorage. The safe sequence is: render the same branch on the server and initial client pass, read storage after hydration, then switch branches with state.
'use client';
import { useEffect, useState } from 'react';
export default function SavedPanel() {
const [hasSavedItems, setHasSavedItems] = useState(false);
const [ready, setReady] = useState(false);
useEffect(() => {
try {
setHasSavedItems(window.localStorage.getItem('saved-items') !== null);
} finally {
setReady(true);
}
}, []);
if (!ready) {
return <div aria-busy='true'>Checking saved items…</div>;
}
return hasSavedItems
? <SavedItems />
: <EmptyState />;
}
The loading branch is rendered on both server and initial client render. Only after the effect completes does the component choose between the two browser-dependent branches. If showing a loading state is unacceptable, move the preference into a request-readable input or make the entire panel client-only.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Framework-specific boundaries matter
Next.js and React
React’s rule is framework-independent: the first client render must match the server output. Next.js adds several rendering modes, including Server Components, Client Components, streaming, and dynamic imports. Confirm which mode your route uses and whether a component is being prerendered before choosing an API. The Next.js documentation summarizes the requirement as: “Ensure that the component renders the same content server-side as it does during the initial client-side render to prevent a hydration mismatch.”
Effects are client-only, making them suitable for deferred browser reads. A dynamic import with ssr: false is suitable for an isolated component that cannot render on the server. Keep the two decisions separate: an effect preserves server HTML with a delayed value; disabling SSR removes server rendering for that component.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Nuxt 2
The cited Nuxt guidance is specifically for Nuxt 2. It recommends accessing window or document in beforeMount or mounted, and describes client-only import handling with process.client. It also notes that divergent server and client output can produce a NodeMismatch. Do not copy these APIs blindly into newer Nuxt releases; check the documentation for the exact version and its current server/client lifecycle conventions.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Remedy comparison
| Remedy | Stable server fallback needed? | Value present in initial HTML? | Post-hydration change | Server-rendered output | Best use |
|---|---|---|---|---|---|
| Read in an effect | Yes | No; value arrives after hydration | Usually yes | Preserved | Preferences and storage-backed UI that can start with a neutral default |
| Client-only dynamic boundary | Only a loading or placeholder UI | No | Component appears after loading | Omitted for that component | Widgets that require the DOM or fail during module initialization |
| Server-readable input | Yes, derived from the request | Yes | Optional synchronization | Preserved with the correct value | State that must shape the first response |
suppressHydrationWarning |
No, but the difference must be intentional | Server value remains subject to React’s suppression behavior | Managed by your code | Preserved, but mismatch is not repaired | Small, unavoidable text differences such as a timestamp |
Common failed approaches and how to repair them
“I added typeof window, so it is fixed.”
The guard prevents an exception only when both branches render equivalent output. If the browser branch reads storage, time, viewport size, or another changing value, the first client render can still differ. Replace the render-time branch with a stable state and an effect, or pass the value from the server.
“The file has 'use client', so it cannot run on the server.”
In Next.js, Client Components can be prerendered. Move the browser access into an effect, or place the component behind a supported client-only dynamic boundary.
“I put the read in a state initializer.”
State initializers execute during rendering, including the server pass. Initialize with a deterministic value and perform the browser read in an effect.
“I suppressed the warning and moved on.”
Suppression hides a selected warning but leaves the underlying output difference. It can also prevent React from patching text. Use it only for a deliberate, localized exception; otherwise correct the data flow.
“The component is safe, but importing it still crashes.”
Inspect top-level code in the component and its dependencies. A browser API accessed while a module is evaluated runs before your effect or event handler. Dynamically import the browser-only module, choose a server-safe build, or move initialization into a client lifecycle step.
“The warning remains after removing storage.”
Check invalid element nesting, calls to Date() or other time-dependent APIs, random values, locale-sensitive formatting, extension-modified markup, CSS-in-JS setup, and edge or CDN transformations. Hydration diagnostics are about output equality, not only browser globals.
Verification after making the change
- Render on the server. Exercise the route in the production-like server runtime and confirm that no browser global is accessed during module loading or render.
- Inspect the response HTML. Verify that the fallback or server-provided value is present and that the structure is complete enough for the browser to hydrate.
- Run a clean browser session. Test with empty storage, populated storage, disabled storage, and malformed stored data. Use a fresh profile or private window to avoid extensions and stale state masking the issue.
- Observe the first render. Confirm that the browser initially displays the same text, attributes, and element structure as the response HTML. Then confirm that the effect or client-only import changes the UI only after hydration.
- Test slow and failed conditions. Throttle the network, block the dynamic chunk, and simulate storage errors. The fallback should remain usable and accessible, and a failed browser read should not turn into a server error.
- Check framework output. Review server logs for exceptions and browser logs for hydration warnings. A clean console is useful, but also verify the actual DOM and keyboard behavior after the delayed update.
A practical decision path
- Can the component render useful, identical initial content without the browser value? If yes, render that deterministic fallback and load the value in an effect.
- Must the value affect the first HTML? If yes, expose it through a request-readable input and pass it into the render path. Do not expect the server to read the browser’s local storage directly.
- Can the component not render meaningfully without the DOM, or does its dependency crash at import time? Isolate it behind the framework’s client-only boundary and accept that its server output is unavailable.
- Is the difference tiny, deliberate, and unavoidable? Only then consider
suppressHydrationWarning, limited to the affected element. - Does the warning persist? Compare server HTML with the first client render and investigate time, randomness, invalid markup, extensions, styling configuration, and response mutation.
Browser APIs are not inherently incompatible with SSR. The failure occurs when code assumes that rendering happens in a browser, or when the server and the first client render make different decisions. Once those phases are treated separately, the repair is straightforward: keep initial output deterministic, move browser work to the correct lifecycle, and use a narrowly scoped client-only boundary only when server rendering is genuinely impossible.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

