Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by pparnxoxo
The "ReferenceError: window is not defined" error occurs for multiple reasons:
window
in Node.js.window
on the server (e.g. server side rendering in Next.js).window
global variable (should be all lowercase).The window represents a window containing a DOM document and is only available in the browser.
window
variable in Node.If you are getting "ReferenceError: window is not defined" in the browser, try
to move your JS script tag to the bottom of the body
tag:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- Your HTML here --> <!-- 👇️ Script at bottom of body --> <script type="module" src="index.js"></script> </body> </html>
You might have some addons that are ran before the DOM is created.
window
global variable represents the window in which the script is running (browser side).If you're using React.js or Next.js and you need to check if you're on the
browser (can use window
) or on the server (can't use window
), you can do
this in the following way:
if (typeof window !== 'undefined') { console.log('You are on the browser') // ✅ Can use window here } else { console.log('You are on the server') // ⛔️ Don't use window here }
We check if the global window
variable does not have a type of undefined
. If
the window
global is defined, we are on the browser and can use the window
variable.
To solve the"ReferenceError: window is not defined" error, make sure to only
use the window
global variable on the browser. The variable represents a
window containing a DOM document and can't be used on the server side (e.g. in
Node.js).
If you need to define global variables in Node.js
, you can define them using
global
, not window
.
global.test = 'EXAMPLE';
And now we can use the variable in some other file:
import './index.js'; console.log(global.test); // 👉️ "EXAMPLE"
But it's much better to simply export a variable from the index.js
file and
import it as needed.
export const test = 'example';
Now we can import the variable in another file.
import {test} from './index.js'; console.log(test); // 👉️ "example"
This is a much better and more explicit approach than defining global variables.