Skip to content
jshacks.dev
Fundamentals

globalThis and the Global Object in JavaScript Runtimes

The global object has a different name in each runtime, and globalThis is the standard one that works in all of them. See where window, self and global fail.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, Vite and TypeScript logos.

The same line of code, window.localStorage, works in a browser tab and fails with ReferenceError: window is not defined on a server, in a web worker and in a test runner. The reason is that "the global object" is a concept in the language and a different name in each place that runs it. For years, portable libraries carried a block of code that tried window, then self, then global, then this. globalThis replaced that block in ES2020, and learning when each name exists explains most of the "is not defined" errors that touch the environment. This post shows the names, the module scoping rules that remove the old need for globals, how to detect features instead of runtimes, and the risks of writing to the global object. Examples run on Node.js 24. It follows the post on scope and relates to the post on realms, where each realm has a global object of its own.

One object, several names

Each runtime gives the global object a name, and globalThis is always one of its properties.

RuntimeNames that point at it
Browser main threadwindow, self, frames, globalThis
Web worker and service workerself, globalThis
Node.jsglobal, globalThis
Deno and BunglobalThis (and self in Deno)

The check in Node.js shows the relationship.

JavaScript
console.log(globalThis === global);
console.log(typeof window);
console.log(typeof self);
console.log(typeof globalThis.process);
console.log(typeof globalThis.fetch);
console.log(typeof globalThis.structuredClone);
Text
true
undefined
undefined
object
function
function

In Node.js 24, global and globalThis are the same object, there is no window, and the built-ins fetch, structuredClone and process are properties of it. Whether self exists depends on the Node.js version, which is why code that tests typeof self to detect a worker can misfire. globalThis is the only name you can rely on.

The window is not defined error

The error appears when browser-only code reaches a place without a DOM. A framework that renders on the server runs your component on Node.js first, and any top-level read of window fails there.

JavaScript
function readTheme() {
  return window.localStorage.getItem("theme");
}

try {
  readTheme();
} catch (error) {
  console.log(error.name + ": " + error.message);
}

function readThemeSafely() {
  if (typeof window === "undefined") return "light";
  return window.localStorage.getItem("theme") ?? "light";
}

console.log(readThemeSafely());
Text
ReferenceError: window is not defined
light

The typeof guard is the one reliable test for a name that may not exist, because it does not throw on undeclared names. For a framework that renders on the server, the better fix is to read the browser value in code that only runs in the browser, such as an effect or an event handler, and let the server render a default. A guard at every call site is a sign that the browser read should move.

Modules do not write to the global object

Old browser scripts put every top-level var and function on window, which is how libraries collided. ES modules and CommonJS files have their own top-level scope, so nothing leaks unless you ask.

JavaScript
var declaredWithVar = 1;
function declaredFunction() {}

console.log(typeof globalThis.declaredWithVar);
console.log(typeof globalThis.declaredFunction);
console.log(this);

globalThis.sharedFlag = true;
console.log(typeof sharedFlag);
Text
undefined
undefined
undefined
boolean

Neither declaration became a property of globalThis, and top-level this in an ES module is undefined, where a classic script would show the global object. The last two lines show the explicit way to create a global, by assigning to globalThis, after which the bare name sharedFlag resolves through the scope chain to the global. In a CommonJS file, top-level this is module.exports, a third value for the same expression. The post on strict mode explains why the sloppy-mode value, the global object, no longer appears in modern code, and the post on var, let and const covers why var no longer leaks.

Detect a feature, not a runtime

Checking the runtime's name, typeof window, typeof process, tells you less than it seems. A test runner such as jsdom defines window in Node. Edge runtimes define fetch and no process. Bun and Deno define a Node-compatible process. The reliable habit is to test for the capability the code needs.

JavaScript
const hasFetch = typeof globalThis.fetch === "function";
const hasTemporal = "Temporal" in globalThis;
const hasDom = typeof globalThis.document !== "undefined";
const isNode = typeof globalThis.process?.versions?.node === "string";

console.log({ hasFetch, hasTemporal, hasDom, isNode });

const storage = globalThis.localStorage ?? new Map();
console.log(storage instanceof Map);
Text
{ hasFetch: true, hasTemporal: false, hasDom: false, isNode: true }
true

On Node.js 24.1, which produced the output above, hasTemporal is false because the Temporal API is not enabled by default there, so check your own runtime and do not assume. Each flag asks about one thing. The in operator is the right test for a property that may legitimately hold a falsy value, and typeof is right for a function or object you intend to call. The last two lines show a fallback pattern: use the real localStorage when present, and an in-memory Map otherwise, which lets the same module run in tests and on a server. We name the flag after the capability and not the environment, since the environment list keeps growing.

Writing to the global object

Adding properties to globalThis makes them visible to every module in the process, which suits two jobs and little else. A polyfill assigns a missing built-in so that the rest of the code can assume it exists. A test setup file installs a mock for the duration of a run.

JavaScript
if (typeof globalThis.structuredClone !== "function") {
  globalThis.structuredClone = (value) => JSON.parse(JSON.stringify(value));
}

const original = { id: 1, tags: ["a"] };
const copy = structuredClone(original);
copy.tags.push("b");

console.log(original.tags);
console.log(copy.tags);
Text
[ 'a' ]
[ 'a', 'b' ]

The guard installs the fallback only when the built-in is missing, so a runtime that provides the real one is never overridden. That conditional is the safe shape for any polyfill. Using the global object as a place to share application state is a different story: two modules that both write globalThis.config overwrite each other, tests leak state between files, and nothing documents the dependency. Pass values as arguments or export them from a module, and the dependency shows up in an import.

The property attributes

The global object has one property whose attributes are worth knowing, because it explains why you cannot delete or enumerate it casually.

JavaScript
const descriptor = Object.getOwnPropertyDescriptor(globalThis, "globalThis");

console.log(descriptor.writable, descriptor.enumerable, descriptor.configurable);
console.log(Object.keys(globalThis).includes("globalThis"));
console.log(Object.getOwnPropertyNames(globalThis).includes("Array"));
Text
true false true
false
true

The name globalThis is writable and configurable but not enumerable, so Object.keys() skips it, and the same is true of built-ins like Array. Listing the global object's enumerable keys shows only what was added by the runtime or by code, which varies by runtime and version, so do not write code that depends on the exact list.

Environments that fake it

Test runners and sandboxes complicate the picture. jsdom and happy-dom create a window inside Node.js, and Vitest can run each test file in its own global. Node's vm module creates a new context whose global object is different from the parent's, so a polyfill installed in one is invisible in the other.

For these cases the rule is again to detect what you need. A library that tests typeof window will think it is in a browser inside jsdom, and typeof document.createElement would be a better test of whether a DOM exists. If your library must behave differently in a server render, expose the choice as an option and not an environment sniff.

Where globalThis does not help

If you are targeting an engine older than the ES2020 era, such as a very old embedded runtime, globalThis may be missing, and a one-line polyfill is needed. Every current browser and Node.js version has had it for years, so for ordinary web and server work this is not a concern.

globalThis also cannot give you a DOM. Code that needs the DOM on the server needs a DOM implementation, or needs to move to the client.

The object is defined in the specification as the global object, and MDN's page for globalThis lists the names per environment.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.