window is not defined error in Next.js: solutions
Analysis of the causes of the window is not defined error in Next.js and React. Effective methods for isolating browser code, dynamic imports, and conditional rendering.
Fixing the window is not defined error in Next.js and React: practical scenarios
The “window is not defined” error in Next.js and React occurs due to browser-specific code executing on the server in SSR or SSG environments where the window object is absent. Solutions include execution environment checks, lifecycle hooks, dynamic imports of components without SSR, or client directives.
Cause of failure in hybrid rendering
In the Next.js framework, component code executes by default in two environments: on the server (Node.js) during server-side rendering (SSR) or static site generation (SSG), and on the client in the browser environment. The global window object, as well as document, localStorage, and navigator, exist exclusively in the browser's Web API. When the server attempts to render a page, Node.js encounters a reference to the non-existent window object, causing the process to crash with a ReferenceError: window is not defined.
Software system architecture quality and exception handling are governed by the GOST R ISO/IEC 25010-2015 standard. To ensure web application fault tolerance, server and client logic must be clearly separated at the build design stage.
Method 1. Checking for window object via typeof window
The quickest way to prevent browser code execution on the server is to add a conditional type check of the global variable before calling browser APIs.
typescript if (typeof window !== 'undefined') { const theme = localStorage.getItem('theme'); console.log('Screen width:', window.innerWidth); }
This approach suits isolated helper functions, utilities, and service files. However, when working with React components, direct use of conditional constructs in the function body can cause a hydration mismatch error, when the server-generated HTML differs from the initial client tree.
Method 2. Isolating DOM access in useEffect and useLayoutEffect hooks
In React, the useEffect hook is guaranteed to run only on the client side after the component mounts in the DOM tree. The server renderer completely ignores useEffect contents.
Step-by-step algorithm for safe browser parameter reading:
- Declare component state with a default value (e.g.,
nullor a base number).
- Place the
windoworlocalStoragecall inside theuseEffectcallback function.
- Update component state via the setter function.
tsx import { useState, useEffect } from 'react';
export default function ScreenWidth { const [width, setWidth] = useState<number | null>(null);
useEffect( => { setWidth(window.innerWidth);
const handleResize = => setWidth(window.innerWidth); window.addEventListener('resize', handleResize); return => window.removeEventListener('resize', handleResize); }, []);
if (width === null) return <div>Loading…</div>; return <div>Window width: {width}px</div>; }
Method 3. Dynamic import of components with SSR disabled
Many third-party libraries (maps, charts, WYSIWYG editors) access window immediately upon module import at the top level. In such cases, a regular import breaks the server build.
To solve this, Next.js uses the dynamic utility from next/dynamic with server-side rendering disabled:
tsx import dynamic from 'next/dynamic';
const ChartNoSSR = dynamic( => import('../components/InteractiveChart'), { ssr: false } );
export default function Page { return ( <main> <h1>Analytics Dashboard</h1> <ChartNoSSR /> </main> ); }
Using dynamic imports aligns with the classification and modularity principles of interactive systems per GOST R 59277-2020.
Comparison of window is not defined error solutions in Next.js
- typeof window !== 'undefined' check: Utilities, helpers, synchronous functions. Preserves SSR, skips code on server. Low complexity.
- useEffect hook: React components, DOM event subscriptions. Code runs strictly after hydration. Low complexity.
- next/dynamic with { ssr: false }: Heavy UI modules, maps, charts, editors. Excludes component from server HTML. Medium complexity.
- 'use client' directive: Client interactive components in App Router. Allows client hooks. Low complexity.
Method 4. Architecture separation in App Router via use client directive
In Next.js 13+ (App Router architecture), all components are server components by default. They execute strictly on the server and lack Web API access.
To convert a component to a client component, add the 'use client' directive as the very first line of the file:
tsx 'use client';
import { useEffect } from 'react';
export default function ClientButton { useEffect( => { console.log('User agent:', window.navigator.userAgent); }, []);
return <button onClick={ => alert(window.location.href)}>Share</button>; }
Note: adding the 'use client' directive does not mean the component renders exclusively in the browser. It still passes through a preliminary SSR HTML rendering stage, so direct window access outside the useEffect hook in a client component will still throw an error.
Typical errors when integrating third-party browser libraries
When developing complex web interfaces, developers often encounter related local environment and build issues:
- Importing a library in the global
_app.tsxorlayout.tsxfile without isolation.
- Running the local development server at
http://127.0.0.1:3000without checking resource collection errors in the console.
- Attempting to access
windowinsidegetServerSidePropsorgetStaticPropsfunctions (these functions execute exclusively in the Node.js environment).
If you need quality web development, sustainable application architecture, or comprehensive digital transformation, consider e-commerce development and AI assistant implementation from specialists on the company's official website.
Frequently asked questions
Why does the window is not defined error occur during project build via next build?
During the build, Next.js pre-renders pages in a Node.js environment to generate static HTML. If a module or library accesses the window object during initial file loading, the build process halts due to the absence of browser environment objects in Node.js.
Can window be used inside useState during state initialization?
Using window directly in the initial useState value (e.g., useState(window.innerWidth)) is not allowed, as this call would execute on the server. A default base value must be passed, then updated inside the useEffect hook after component mount.
What is the difference between typeof window !== 'undefined' and the useEffect hook for hydration?
The typeof window check allows skipping code execution on the server but can lead to a mismatch between generated HTML and client DOM (hydration mismatch). Using useEffect guarantees code execution strictly after primary page hydration completes.
How to properly integrate third-party libraries like Leaflet or Chart.js in Next.js?
Such libraries request DOM APIs immediately upon import. They should be connected via the next/dynamic tool with SSR disabled ({ ssr: false }) or via dynamic import inside useEffect.
Material prepared by: aiforsale.ru Editorial Team, Domain Expert.
Web development, digital advertising and marketing expert since 2012. Founder of AIFORSALE.