Fix Next.js Error: window is not defined (2025 Guide)

Fix Next.js Error: window is not defined (2025 Guide)
Posted on: April 15, 2025
Encountered an "Error: window is not defined" in Next.js? This error occurs when you try to access the `window` object during server-side rendering or static site generation. Let’s fix it fast in this 2025 guide!
What Causes "Error: window is not defined"?
This error happens because Next.js renders pages on the server where `window` (a browser-specific object) is unavailable. Common causes include:
- Direct Window Access: Using `window` in a component or function without checking the environment.
- Third-Party Libraries: Libraries that assume a browser context.
- Dynamic Imports Missing: Failing to use client-side only imports.
Check this demo (open console with F12):
Here, the code checks for `window` and logs an error when it’s undefined, simulating a server-side context.
How to Fix It: 3 Solutions
Let’s resolve this error with practical steps:

(Diagram: Developer accesses window, gets error, moves to client-side, runs successfully.)
Solution 1: Use useEffect for Client-Side Logic
Move `window`-dependent code to `useEffect` to ensure it runs only on the client:
// Wrong
function MyComponent() {
const width = window.innerWidth;
return Width: {width};
}
// Fixed
import { useState, useEffect } from 'react';
function MyComponent() {
const [width, setWidth] = useState(0);
useEffect(() => {
setWidth(window.innerWidth);
}, []);
return Width: {width};
}
export default MyComponent;
`useEffect` ensures `window` is accessed only after the component mounts on the client.
Solution 2: Use Dynamic Import with ssr: false
Import client-side only components dynamically with `ssr: false`:
import dynamic from 'next/dynamic';
const ClientComponent = dynamic(() => import('../components/ClientComponent'), {
ssr: false // Disable server-side rendering for this component
});
export default function Page() {
return ;
}
This prevents the component from being rendered on the server, avoiding the `window` error.
Solution 3: Check for Window Availability
Use a conditional check to ensure `window` is defined before accessing it:
import { useState } from 'react';
function MyComponent() {
const [isClient, setIsClient] = useState(false);
if (typeof window !== 'undefined' && !isClient) {
setIsClient(true);
}
return (
{isClient && Window width: {window.innerWidth}}
);
}
export default MyComponent;
Checking `typeof window !== 'undefined'` ensures the code runs only in a browser context.
Quick Checklist
- Using `window` directly? (Move to `useEffect`)
- Client-side only code? (Use `dynamic` with `ssr: false`)
- Need a fallback? (Check `typeof window`)
Conclusion
The "Error: window is not defined" in Next.js can be fixed by ensuring `window`-dependent code runs only on the client. With these 2025 solutions, your app will stay stable. Got another Next.js error? Let us know in the comments!
Comments
Post a Comment