ReferenceError : window is not defined at object. Node.js

window is a browser thing that doesn’t exist on Node.js, but ES2020 introduced globalThis, which (being part of the JavaScript specification) is available on both compliant browser engines and in Node.js.

If you really want to create a global in Node.js, use globalThis or (for older versions) global:

// BUT PLEASE DON'T DO THIS, keep reading
globalThis.windowVar = /*...*/:
// or
global.windowVar = /*...*/; 

global is Node’s identifier for the global object (defined in their API before globalThis existed), like window is on browsers. For code that may run in a wide range of environments, including older ones:

const g = typeof globalThis === "object"
    ? globalThis
    : typeof window === "object"
        ? window
        : typeof global === "object"
            ? global
            : null; // Causes an error on the next line
g.windowVar = /*...*/;

But, there’s no need to create truly global variables in Node programs. Instead, just create a module global:

let /*or `const`*/ windowVar = /*...*/;

…and since you include it in your exports, other modules can access the object it refers to as necessary.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)