← Back to JavaScript, page 7

javascript-0128 · Easy fresher

How do Node.js and the browser differ as JavaScript environments, in globals, modules, and available APIs?

Both run the same language, but the global object and the APIs around it differ. Browsers provide window, document, and Web APIs for the page, while Node.js provides process, Buffer, file system, and network modules, and has no DOM. Modern Node.js also includes many web standard APIs such as fetch, URL, and AbortController. Use globalThis and feature detection when code must run in both.

Full answer

JavaScript the language (ECMAScript) is the same in both. What differs is the host environment: the global object, the built-in APIs, the module system, and the security model.

Browser: the global object is window (and self in workers). It provides document and the DOM, location, history, localStorage, fetch, XMLHttpRequest, alert, requestAnimationFrame, and many more Web APIs. Scripts run in a sandbox with same-origin rules and cannot read files freely.

Node.js: a server-side runtime. The global object is global, and globalThis works everywhere. There is no window or document. It provides process (arguments, environment variables, exit codes), Buffer, and built-in modules such as fs, path, http, crypto, and child_process. Node can read files and open sockets, so it has no sandbox by default.

Standard APIs shared today: fetch, URL, URLSearchParams, AbortController, TextEncoder, structuredClone, setTimeout, queueMicrotask, performance, and EventTarget exist in both, although small details differ. One known difference: setTimeout returns a number in browsers and a Timeout object in Node.js.

Modules: browsers use ES modules (<script type="module">). Node.js supports both CommonJS (require, module.exports, __dirname) and ES modules (import, import.meta.dirname), chosen by the file extension (.mjs or .cjs) or the type field in package.json. require and __dirname do not exist in ES module files.

Top level this: in a browser script it is window; in a Node.js CommonJS module it is module.exports; in an ES module it is undefined.

For code that must run in both, avoid assuming either side. Use globalThis, check for a feature (typeof document !== 'undefined') instead of checking the browser name, and keep environment-specific code in separate modules. This matters for server-side rendering, where code written for the browser runs once on the server.

javascript
const has = (name) => typeof globalThis[name] !== 'undefined';

console.log('browser globals present:', ['window', 'document', 'localStorage', 'alert'].map((n) => `${n}=${has(n)}`).join(' '));
console.log('node globals (typeof):', typeof process, typeof Buffer, typeof require, typeof __dirname);
console.log('require and __dirname are module wrappers, not on globalThis:', 'require' in globalThis, '__dirname' in globalThis);
console.log('shared web APIs:', ['fetch', 'URL', 'AbortController', 'structuredClone', 'TextEncoder', 'queueMicrotask', 'performance', 'EventTarget'].map((n) => `${n}=${has(n)}`).join(' '));

console.log('globalThis is global:', globalThis === global, '| window is undefined:', typeof window);
const isNode = typeof process !== 'undefined' && Boolean(process.versions?.node);
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
console.log({ isNode, isBrowser });

const timer = setTimeout(() => {}, 0);
console.log('setTimeout returns:', typeof timer, timer.constructor.name);
clearTimeout(timer);

console.log('top level this in CommonJS is module.exports:', this === module.exports);
console.log('file name helpers exist:', typeof __filename, typeof __dirname);

const { readFileSync } = require('node:fs');
console.log('node only module works:', typeof readFileSync);

// a shared function that works in both environments
function currentEnvironment() {
  if (typeof document !== 'undefined') return 'browser';
  if (typeof process !== 'undefined' && process.versions?.node) return 'node';
  return 'unknown';
}
console.log(currentEnvironment());

Run with Node.js v24.22.1 as js-128.js; two runs gave identical output. Output: browser globals present: window=false document=false localStorage=false alert=false node globals (typeof): object function function string require and __dirname are module wrappers, not on globalThis: false false shared web APIs: fetch=true URL=true AbortController=true structuredClone=true TextEncoder=true queueMicrotask=true performance=true EventTarget=true globalThis is global: true | window is undefined: undefined { isNode: true, isBrowser: false } setTimeout returns: object Timeout top level this in CommonJS is module.exports: true file name helpers exist: string string node only module works: function node

Key points

  • Same language, different host: browsers add window and the DOM; Node.js adds process, Buffer, and system modules.
  • Many web standard APIs are now in both: fetch, URL, AbortController, structuredClone.
  • Node supports CommonJS and ES modules; require and __dirname are not available in ES modules.
  • setTimeout returns a number in browsers and an object in Node.js; top-level this differs.
  • Use globalThis and feature detection; separate environment-specific code (important for server-side rendering).

Common mistakes

  • Using window or document in code that also runs on the server.
  • Using require or __dirname in an ES module.
  • Detecting the environment from the user agent instead of checking for the feature.
  • Assuming that all web APIs behave exactly the same in Node.js.

Follow-ups

  • How does top-level this differ in CommonJS, ES modules, and browser scripts?
  • Why does server-side rendering break code that reads window at import time?
  • How do you choose between CommonJS and ES modules in a Node.js project?

Tips

  • Say that the language is the same and the host APIs differ.
  • Mention the shared web standard APIs that reduce the gap.
  • Show feature detection with typeof and globalThis.