To solve reference error: window is not defined in JavaScript, add an if statement inside which we are using process.browser at the client-side is a predefined function and returns a boolean type.
In this article, we will solve the error when using the next JS. So usually, Next JS uses the SSR (Server side rendering) for the client-side rendering.
Let’s say the HTML page belongs to the client-side this sometimes happens when we try to use the window in the SSR mode, or when we try to use this one; all the libraries we are using by using this window are undefined.
In this article, we will solve this “Window is not defined” error. So let’s see how to do this:
So, here we have a JavaScript code (register.js) below which persists the error:
// Window is not defined
const Register=()=>{
console.log(window.location.pathname);
return (<div>
<h1>Solving Window not defined Error</h1>
</div>);
}
export default Register;
This code will generate a server error ‘window is not defined’. So let’s see how to fix it.
Solving reference error: window is not defined in JavaScript
// Fixing Window is not defined
const Register = () => {
if (process.browser) {
console.log(window.location.pathname);
}
return (<div>
<h1>Solving Window not defined Error</h1>
</div>);
}
export default Register;
Here we are adding an if statement inside which we are using the process.browser which is a predefined function and returns a boolean type. This function is used client-side.
So that means if we are on the client-side we can use this function for window operations. We can write window operations inside this ‘if’ statement and this is how we will be able to fix the ‘window not defined’ error.
Now if we want to print the window on an HTML page. The refer to the following code.
// Fixing Window is not defined
const Register = () => {
if (process.browser) {
console.log(window.location.pathname);
}
return (<div>
<h1>Solving Window not defined Error</h1>
{process.browser && window.location.pathname}
</div>);
}
export default Register;
We have added {process.browser && window.location.pathname} inside return so as soon as a process.browser returns true we are executing window.location.pathname on the browser.
To get the full URL instead of the page name in the window we can replace “pathname” with “href”.
That’s it for this tutorial.
See also
How to solve reference error: window is not defined
How to Use a Debugger in JavaScript

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.