How to Fix 'window is not defined' Error in Next.js
window is not defined error in Next.js happens because window is only available in the browser, not on the server during server-side rendering. To fix it, access window inside a useEffect hook or check if typeof window !== 'undefined' before using it.Why This Happens
Next.js runs code both on the server and in the browser. The window object exists only in the browser environment. When you try to use window directly in your component code, Next.js tries to run it on the server first, causing the error.
export default function MyComponent() { console.log(window.location.href); return <div>Hello</div>; }
The Fix
To fix this, use the window object only inside a useEffect hook, which runs only in the browser after the component mounts. Alternatively, check if window exists before using it.
import { useEffect, useState } from 'react'; export default function MyComponent() { const [url, setUrl] = useState(''); useEffect(() => { setUrl(window.location.href); }, []); return <div>Current URL: {url}</div>; }
Prevention
Always remember that Next.js code runs on both server and client. Avoid using browser-only objects like window, document, or localStorage directly in the main body of your components. Use useEffect or conditional checks like typeof window !== 'undefined' to safely access them.
Using linting tools with rules for Next.js can help catch these mistakes early.
Related Errors
Similar errors include document is not defined and localStorage is not defined. They happen for the same reason: trying to use browser-only objects during server-side rendering. The fix is the same: use useEffect or check if the object exists before using it.