[Solved] ReferenceError : window is not defined

Total
1
Shares

The ReferenceError : window is not defined error mainly occurs if you are using the window object in Node.js, React.js, Next.js. The window object mainly exists in the browser context and not on the server context.

In this tutorial, we will look at what exactly is ReferenceError : window is not defined means and how to resolve this error with examples.

Let us look into some basics first.

ReferenceError: This class of error occurs when we try to reference a variable that does not exist in the current scope or is waiting for initialization.

Window: It denotes a window containing a DOM document and it is only available in browser context.

What is ReferenceError : window is not defined?

Now we will examine various reasons for the occurrence of this error.

1. In the case of using window in Node.js

As explained above, window contains a DOM document and is only available in the browser. Node.js does not support a browser environment. Node is a server-side runtime, ‘window‘ variable does not work for it.

2. In the case of using window in next.js/React.js

Next.js can render React on the client as well as on the server. It generally pre-renders the page using the node server. In this particular setup, we cannot access window. This causes the reference error.

3. Misspelled /Misplaced ‘window’ variable

Sometimes this error also occurs on the browser where it is configured to run correctly. Error on the browser end generally happens if we misplace the JavaScript script tag or misspell the window global variable.

How to fix ReferenceError : window is not defined?

The solution depends on where you are trying to access the window object. Let us take a look at each of the scenarios.

Solution 1: Check whether browser or server-side execution

In the case of React/Next.js applications, we can check the execution environment beforehand. If the window is defined (browser), the execution will continue. 

Let us look at the code snippet on how to check if window object exists.

if (typeof window !== 'undefined') {
  console.log('You are on the browser,You are good to go')
  } else {
  console.log('You are on the server,Cannot execute')
 }

We use the built-in typeOf operator to confirm that the window is defined. If it is defined, then the window execution takes place. We must remember that ‘undefinedshould always be in single quotes, or the comparison will fail.

if (typeof window !== undefined) {
  console.log('You are on the browser,You are good to go')
  } else {
  console.log('You are on the server,Cannot execute')
 } // It will always go in else block

Solution 2: If error occurs while running on browser

The window is not defined reference error may also occur in case of browser execution. It can happen due to misspelled keywords or a mispositioned script tag.

Let us discuss this with an example.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <!-- HTML Code here -->

    <!-- Script tag at bottom of body -->
    <script type="" src="test.js"></script>
  </body>
</html>

There might be some addons/Library inclusions that must be included before DOM creation. If we invoke the Script tag before the addons, it may give an error.

Secondly, a spelling error can also cause this malfunction. There is a big difference between ‘Window‘ and ‘window

Window: is a function, the constructor of the windows.

window: is the global variable representing the browser window containing your document.

Let us take a simple example to demonstrate the difference between Window and window

var countVal = 1; 
var showCount = () => console.log(countVal); 
console.log(window.countVal); 
window.showCount();

Output

1 
counter 1
var countVal = 1; 
var showCount = () => console.log(countVal); 
console.log(Window.countVal); 
Window.showCount(); 

// Output: Uncaught TypeError: Window.showCount is not a function

How to use Global variable in Node.js?

If you need to define global variables in Node.js, then we can define them using global, not window.

Let us take a simple example to see how it works

global.count = 5;

// Better way is to export the variable
export const count = 5;

Now we can import this in any of the files and use this constant.

import {count} from './main.js';


console.log(count); 

// Output: 5

Conclusion

We can conclude that we cannot use window on the server environment as they were developed to run on the browser, doing that will result in ReferenceError : window is not defined.

We can solve this issue on React.js and Next.js code using typeOf operator and we can check the reference variable exists. If the error occurs on the browser, check placement and syntax for window object.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified on the latest articles

You May Also Like
JavaScript Array slice()

JavaScript Array slice()

Table of Contents Hide slice() Exampleslice() Syntaxslice() Parametersslice() Return ValueExample 1: Clone an array using the JavaScript slice() methodExample 2: JavaScript slice() methodExample 3: JavaScript slice() With Negative indexExample 4:…
View Post
JavaScript String padEnd()

JavaScript String padEnd()

Table of Contents Hide padEnd() ExamplepadEnd() SyntaxpadEnd() ParameterpadEnd() Return ValueExample 1 – How padEnd() method works in JavaScript?Example 2 – Working of padEnd() method with default value In this tutorial,…
View Post
JavaScript String toLowerCase()

JavaScript String toLowerCase()

Table of Contents Hide toLowerCase() ExampletoLowerCase() SyntaxtoLowerCase() ParametertoLowerCase() Return ValueExample: JavaScript Convert string from uppercase to lowercase In this tutorial, we will learn about the JavaScript String toLowerCase() method with…
View Post