The “window not defined” error in Next.js usually occurs when you try to access the window
object on the server-side, which is not available because the server does not have a window. To resolve this issue, you need to ensure that the code that tries to access the window
object only runs on the client-side.
Here’s an example of how to resolve the “window not defined” issue in Next.js:
First, identify the code that tries to access the window
object. In this example, let’s say we have a component that uses the window
object to get the current width of the screen:
import { useState, useEffect } from 'react';
function MyComponent() {
const [width, setWidth] = useState(0);
useEffect(() => {
setWidth(window.innerWidth);
}, []);
return (
<div>
<p>Width: {width}</p>
</div>
);
}
export default MyComponent;
To fix the “window not defined” error, we need to make sure that the code that accesses the window
object only runs on the client-side. We can do this by wrapping the code in a check for the window
object:
import { useState, useEffect } from 'react';
function MyComponent() {
const [width, setWidth] = useState(0);
useEffect(() => {
if (typeof window !== 'undefined') {
setWidth(window.innerWidth);
}
}, []);
return (
<div>
<p>Width: {width}</p>
</div>
);
}
export default MyComponent;
Now, when the code runs on the server-side, the window
object will be undefined and the code inside the if
block will not be executed. When the code runs on the client-side, the window
object will be available and the code inside the if
block will be executed, setting the width
state to the current width of the screen.