0
0
NextjsDebug / FixBeginner · 3 min read

How to Fix 'window is not defined' Error in Next.js

The 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.

javascript
export default function MyComponent() {
  console.log(window.location.href);
  return <div>Hello</div>;
}
Output
ReferenceError: window is not defined
🔧

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.

javascript
import { useEffect, useState } from 'react';

export default function MyComponent() {
  const [url, setUrl] = useState('');

  useEffect(() => {
    setUrl(window.location.href);
  }, []);

  return <div>Current URL: {url}</div>;
}
Output
Current URL: http://localhost:3000/
🛡️

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.

Key Takeaways

The window object is only available in the browser, not during server-side rendering.
Use useEffect to access window safely after the component mounts.
Check if window exists with typeof window !== 'undefined' before using it.
Avoid using browser-only objects directly in component body code.
Lint your code to catch unsafe window usage early.