Skip to content

globalThis: one global object everywhere (ES2020)

  • Why reaching the global object used to need environment-specific code.
  • What globalThis is, its property attributes, and how it relates to window, self and global.
  • Which declarations appear on it, and why each realm has its own.
  • When writing to the global object is justified.

TL;DR: globalThis is a standard global property that refers to the global this value, which in browsers and Node.js is the global object. It works the same way in windows, web workers, Node.js, Deno and Bun, and in modules and strict code where top-level this is undefined. It was added in ECMAScript 2020.

Each host named its global object differently: window in browser windows, self in windows and workers, global in Node.js. Libraries and polyfills had to probe for each name. The universal fallback, Function('return this')(), is blocked by a Content Security Policy that disallows eval, and top-level this is undefined in modules and strict functions.

Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The output shown under each sample was produced with Node.js 22.23.

// Before ES2020: probe for the global object environment by environment.
function getGlobalLegacy() {
if (typeof self !== 'undefined') return self; // browsers and workers
if (typeof window !== 'undefined') return window; // browsers
if (typeof global !== 'undefined') return global; // Node.js
return Function('return this')(); // blocked by a strict CSP
}
console.log(getGlobalLegacy() === globalThis);
console.log(typeof window, typeof self, typeof global);
// In an ES module, top-level `this` is undefined, so it cannot be used either.
console.log(this);
// ES2020: one name everywhere.
console.log(globalThis === global, globalThis.Math === Math);
const { writable, enumerable, configurable } = Object.getOwnPropertyDescriptor(globalThis, 'globalThis');
console.log({ writable, enumerable, configurable });

Output:

true
undefined undefined object
undefined
true true
{ writable: true, enumerable: false, configurable: true }

The specification defines globalThis as a property of the global object whose initial value is the realm’s global this value. It is writable and configurable but not enumerable. As MDN notes, being writable and configurable lets code hide or replace it before running untrusted code, so the global object is not exposed.

  • Browsers do not hand out the real global object. globalThis, window and self in a window all return a WindowProxy that forwards to the current page’s global object, so globalThis === window is true.
  • Workers have no window; globalThis === self there.
  • Node.js keeps global as an alias; globalThis === global.
  • Hosts may differ. The spec lets a host provide a global this value that is not the global object itself, though browsers, Node.js, Deno and Bun all use the global object (or its WindowProxy).

The name was chosen because global and self would have broken existing code (see the proposal’s naming notes).

import vm from 'node:vm';
// 1. Module-level declarations never become global properties.
var moduleVar = 1;
const moduleConst = 2;
console.log('moduleVar' in globalThis, 'moduleConst' in globalThis);
// 2. Writing to globalThis creates a real global variable.
globalThis.ordersPortalBuild = '2026.11';
console.log(ordersPortalBuild);
delete globalThis.ordersPortalBuild;
console.log(typeof ordersPortalBuild);
// 3. globalThis is an ordinary writable property, so it can be shadowed or overwritten.
{
const globalThis = { fake: true };
console.log(globalThis.fake);
}
// 4. Each realm (iframe, worker, vm context) has its own globalThis and built-ins.
const otherRealm = vm.runInNewContext('globalThis');
const foreignArray = vm.runInNewContext('[1, 2, 3]');
console.log(otherRealm === globalThis);
console.log(foreignArray instanceof Array, Array.isArray(foreignArray));

Output:

false false
2026.11
undefined
true
false
false true

In a classic (non-module) script, top-level var and function declarations do become properties of globalThis, but top-level let, const and class do not; they live in the global lexical scope described in Block bindings. In a module, nothing declared at the top level is added.

The last two lines show realms. Every iframe, worker and vm context has its own global object with its own Array, Object and Error, so an array from another realm fails instanceof Array here, while Array.isArray works across realms.

Several OrdersPortal bundles on one page may include the same telemetry queue, sometimes in different versions. To keep one queue per page, the module stores it on globalThis under a registered symbol, non-enumerable and read-only, and feature-detects navigator.sendBeacon without assuming window exists.

// telemetry.mjs - one OrdersPortal telemetry queue per realm, even if the
// bundler ships two copies of this module (for example two package versions).
const KEY = Symbol.for('ordersportal.telemetry'); // shared across copies in one realm
function createQueue(version) {
const events = [];
return {
version,
track(name, data = {}) {
events.push({ name, ...data });
},
flush() {
return events.splice(0);
},
};
}
export function getTelemetry(version) {
// Feature-detect a host API without assuming window, self or global exists.
const hasBeacon = typeof globalThis.navigator?.sendBeacon === 'function';
if (!globalThis[KEY]) {
Object.defineProperty(globalThis, KEY, {
value: { ...createQueue(version), hasBeacon },
enumerable: false, // keep it out of for...in over the global object
writable: false,
configurable: false,
});
}
return globalThis[KEY];
}
// Two "copies" of the module asking for the queue.
const fromCopyA = getTelemetry('1.4.0');
const fromCopyB = getTelemetry('2.0.1');
fromCopyA.track('checkout_started', { orderId: 'ord-1042' });
fromCopyB.track('checkout_completed', { orderId: 'ord-1042' });
console.log(fromCopyA === fromCopyB, fromCopyB.version, fromCopyB.hasBeacon);
console.log(fromCopyB.flush());

Output in Node.js 22, which has a global navigator but no sendBeacon:

true 1.4.0 false
[
{ name: 'checkout_started', orderId: 'ord-1042' },
{ name: 'checkout_completed', orderId: 'ord-1042' }
]

Symbol.for returns the same symbol for the same string within a realm, so both copies find the same slot, which cannot collide with an ordinary global. The first version to load wins (1.4.0 here), so real code should check compatibility. Polyfills follow the same pattern: test typeof globalThis.SomeApi === 'undefined', then install with Object.defineProperty as non-enumerable, writable and configurable, like built-ins.

  • Using the global object as an application store. Globals are shared by every script on the page and are hard to test. Pass dependencies explicitly or use module-level state.
  • Global state in server-side rendering. One Node.js process serves many requests, so data written to globalThis during one request leaks into the next user’s response. Keep per-request data request-scoped (for example with AsyncLocalStorage).
  • Assuming one globalThis per page. Iframes and workers have their own, with their own built-ins, so instanceof checks fail across them.
  • Treating globalThis as tamper-proof. It is writable and can be shadowed. Security code should not trust it.

Use globalThis when code must reach the global object without knowing the host: polyfills, environment-agnostic libraries, feature detection (test for the API you need, not the environment) and symbol-keyed singletons. Avoid global state when an import or a parameter would do.

According to MDN’s browser compatibility data, globalThis is supported in Chrome 71, Edge 79, Firefox 65, Safari 12.1 (iOS 12.2), Node.js 12.0.0, Deno 1.0 and Bun 1.0. Internet Explorer and legacy Edge never supported it. TypeScript has type-checked globalThis since version 3.4: global var declarations, including declare global { var ordersPortalBuild: string } in a module, become properties of typeof globalThis (checked with TypeScript 5.9). For older runtimes, core-js and the globalthis package on npm provide polyfills that use the probing shown above.

1. Why was globalThis needed when window already existed? window exists only in browser windows; workers use self, Node.js uses global, top-level this is undefined in modules, and Function('return this')() is blocked by CSP. globalThis is one standard name for all of them.

2. Is globalThis === window in a browser, and is it the real global object? Yes, they are equal, but both are a WindowProxy that forwards to the current page’s global object, not the global object itself.

3. Does const apiBase = '...' at the top of a script create globalThis.apiBase? No. Top-level let, const and class live in the global lexical scope, which other scripts can read but which is not on the global object. In a module, nothing at the top level becomes global.

4. Senior scenario: two micro-frontends on one page each bundle the same analytics library and double-count events. How do you fix it with minimal coupling? Have the library register one instance per realm on globalThis under a Symbol.for key, defined as non-enumerable. Each copy reuses an existing instance after checking a version field for compatibility. Longer term, share the library as a single module (import maps or module federation) so the global slot is only a safety net.

  • globalThis (ES2020) is the global this value in every host; in browsers it is the WindowProxy.
  • It is writable, configurable and non-enumerable, so it can be hidden or shadowed.
  • Module declarations and top-level let/const never appear on it.
  • Each realm has its own globalThis and built-ins.
  • Use it for polyfills, feature detection and symbol-keyed singletons, not as an app-wide store.