Node vs Browser JavaScript

The language is the same, but the available features differ.

Node.js and the browser both run JavaScript, but each provides a different set of tools around the language.

FeatureBrowserNode.js
Global objectwindowglobal
The DOM (document)YesNo
File system accessNoYes (fs)
ModulesES modulesCommonJS & ES modules

The shared core

Variables, functions, arrays, objects, promises, and all the JavaScript syntax you know work the same in both places. Only the surrounding APIs change.

Example

Example · javascript
// This works in Node, but not in a browser:
const os = require('os');
console.log('Running on:', os.platform());

// This works in a browser, but NOT in Node:
// document.querySelector('h1').textContent = 'Hi';

When to use it

  • A developer migrating a browser utility to Node.js discovers `window` is undefined and guards with `typeof window !== 'undefined'`.
  • A team shares validation logic between an Express backend and a React frontend by keeping it free of DOM or Node-specific imports.
  • A Node.js script uses `process.env` and `fs` -- APIs absent in browsers -- to read secrets and write reports to disk.

More examples

Node-only globals

Shows three globals that are available only in Node.js, not in browser JavaScript.

Example · js
// These exist in Node but NOT in the browser
console.log(process.version);  // Node version
console.log(__filename);       // absolute path of this file
console.log(__dirname);        // directory of this file

Browser globals absent in Node

Illustrates that DOM globals like `window`, `document`, and `localStorage` do not exist in Node.js.

Example · js
// Running this in Node.js (pre-18):
typeof window;    // 'undefined'
typeof document;  // 'undefined'
typeof localStorage; // 'undefined'

Isomorphic environment check

A portable runtime detection pattern used in libraries that target both Node.js and the browser.

Example · js
// shared/env.js -- works in both Node and browser
const isNode =
  typeof process !== 'undefined' &&
  process.versions != null &&
  process.versions.node != null;

console.log(isNode ? 'Running in Node' : 'Running in browser');

Discussion

  • Be the first to comment on this lesson.