globalThis Detects The Runtime Realm

Detect Node, worker, or browser once with globalThis and typeof guards so isomorphic code picks the right branch without touching window or global.

TypescriptConfig Management

Code

typescriptsnippet
22 lines
// globalThis is the one global reference that exists in every realm —
// window in browsers, global in Node, self in workers — so runtime
// detection can be written once and typed the same everywhere.
function runtimeName(): 'node' | 'worker' | 'browser' {
  const g = globalThis as typeof globalThis & {
    process?: { versions?: { node?: string } };
    window?: unknown;
    self?: unknown;
  };
  if (typeof g.process !== 'undefined' && g.process.versions?.node) {
    return 'node';
  }
  if (typeof g.self !== 'undefined' && typeof g.window === 'undefined') {
    return 'worker';
  }
  return 'browser';
}

const runtime = runtimeName();
console.log(runtime);
console.log(typeof globalThis);
console.log(typeof window);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

node
object
undefined

One probe for every realm

runtimeName() narrows globalThis with a local type that marks process, window, and self as optional, then asks about them with typeof guards instead of bare references. In Node, typeof g.process !== 'undefined' && g.process.versions?.node matches first and returns 'node'; in a worker, self exists while window does not, giving 'worker'; anything else falls through to return 'browser'. Because the checks are typeof-based, whichever global the realm lacks is simply skipped, never thrown over.

What a bare Node process prints

node
object
undefined

Line one is the probe’s verdict. typeof globalThis is 'object' in every realm — that is what makes the file portable — and typeof window is 'undefined' outside browsers, so nothing here touches window or global directly.

The line that claims Node

if (typeof g.process !== 'undefined' && g.process.versions?.node) {
  return 'node';
}

The versions?.node chain is deliberately stricter than “process exists”: bundled or shimmed process look-alikes without a Node version marker fall through to the next branch.

Interactive Tools for This Topic

FAQ

Does globalThis Detects The Runtime Realm run in plain Node.js?
No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.