Sub topic 3
Global Objects and Environment Detection
This chapter assumes you already know how scripts and modules load in each runtime, and how the event loop schedules promises and timers.
Global Objects
Each runtime has its own global object. In browsers it is window. Node.js uses global, and process carries details about the Node.js process. globalThis refers to the global object in every modern runtime, so use it in shared code.
Check globals with typeof. Reading an undeclared name such as window in Node.js throws a ReferenceError, but typeof window just returns 'undefined'.
const isBrowser =
typeof window !== 'undefined' && typeof window.document !== 'undefined';
const isNode =
typeof process !== 'undefined' && process.versions?.node != null;
console.log({ isBrowser, isNode });Writing Code That Runs Everywhere
Use web-standard APIs that both runtimes provide, such as fetch, URL, TextEncoder, and AbortController. Write the code as an ES module and avoid document, fs, and require. Then the same file runs in both places.
// works in modern browsers and Node.js 18 and later
export async function getJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}Debugging
In browsers, open DevTools and set breakpoints in the Sources panel. For Node.js, run node --inspect-brk app.js, then open chrome://inspect in Chrome. Both give you the same debugger. A debugger; statement pauses execution in either one.
Security Models Compared
| Aspect | Browser | Node.js |
|---|---|---|
| File system | No direct access | Full access through `fs` |
| Network | Limited by same-origin policy and CORS | Unrestricted |
| Trust | Page code is untrusted | Code runs with the user's permissions |
Because Node.js code has no sandbox, every dependency you install can read your files.
Moving Work Off the Main Thread
CPU-heavy loops block the event loop. Browsers provide Worker, and Node.js provides worker_threads. Both send results back with postMessage.
Packages, npm, and Bundlers
npm installs dependencies into node_modules and records them in package.json. Node.js resolves bare imports like import x from 'lodash' directly. Browsers can't do that, so bundlers such as Vite, esbuild, or webpack resolve those imports and merge your modules into fewer, optimized files.
Exercise
Why does if (window) { ... } crash in Node.js, and what should you write instead?
Show answer
window is not declared in Node.js, so reading it throws a ReferenceError. Use typeof window !== 'undefined', or use globalThis when you only need the global object.