Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 133 ยท Getting Started

Node.js vs the Browser

Compare Node.js and browser JavaScript - what is the same, what differs (DOM, modules, globals, security, APIs) and how to write isomorphic code for both.

Node.js and the browser both run JavaScript, so it is tempting to think code moves freely between them. Much of it does: the language, fetch, URL, timers, JSON, promises. But the two environments exist for different jobs, and the differences cause real bugs, such as a browser tutorial's document.getElementById crashing on a server, or a Node script's require failing in a web page.

This lesson draws the map. You will see what the two share, what only one of them has, how their security models differ, and how to write code that runs in both ("isomorphic" or "universal" code).

The same language

The JavaScript language comes from one standard (ECMAScript), and both environments implement it with the V8 engine when the browser is Chrome or Edge. Variables, functions, classes, destructuring, async/await, Map, Set, Promise, JSON, Intl and Math behave identically. A recent Node supports essentially every modern language feature. Safari uses a different engine (JavaScriptCore) and Firefox another (SpiderMonkey), so for browsers you also check that every user's browser supports a feature; with Node you control the version, so you simply read its release notes.

The shared Web APIs are also a big overlap. All of these exist in both worlds: fetch, Request, Response, Headers, URL, URLSearchParams, AbortController, TextEncoder/TextDecoder, structuredClone, setTimeout/setInterval, queueMicrotask, crypto.subtle, Blob, FormData, ReadableStream, performance.now() and the console.

Node.js Code that is identical in both worlds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This exact code could be pasted into a browser console and print the same lines. That is the reason the JavaScript tutorial applies directly to Node.

What the browser has that Node does not

A browser gives JavaScript a page. Almost everything unique to browsers is about showing and interacting with that page:

  • The DOM: document, window, elements, events such as click. Node has none of it.
  • Rendering and layout: getBoundingClientRect, CSS, requestAnimationFrame, canvas drawing, alert.
  • User-facing storage and state: localStorage, sessionStorage, cookies set through document.cookie, history and location.
  • Device APIs behind permission prompts: geolocation, camera, clipboard.

Using any of these in Node fails right away with a ReferenceError. Reading that message is a good skill, so here it is on purpose:

Node.js Using the DOM in Node (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You should see ReferenceError: document is not defined with a line number pointing at main.mjs:2, and the process exits with code 1. The fix is not to define a fake document; it is to move the logic that touches the page into browser-only code. Libraries such as jsdom do implement a DOM in Node, mainly for testing.

What Node has that the browser does not

Node gives JavaScript the machine: the file system, processes and the network at a low level.

  • node:fs reads and writes any file the user running the program can access.
  • node:http, node:net, node:dgram open servers and raw sockets. A browser can only make requests, never listen.
  • node:child_process and node:worker_threads start other programs and threads.
  • node:os, node:path, node:crypto (including the older API), node:zlib, node:stream, node:sqlite and process.
Node.js Things only Node can do

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Modules: the biggest historical difference

Browsers load code with <script type="module"> and import. Node began with its own system, CommonJS (require and module.exports), because ES modules did not exist yet. Today Node fully supports ES modules too, and new code should use them. Differences that still surprise people:

Browser Node.js
Import a file import './util.js' (URL, extension needed) import './util.js' (path, extension needed)
Import a package via URL or bundler/import map import 'pkg' resolved through node_modules
Built-ins none import fs from 'node:fs'
Old style none require() in CommonJS
Top-level await yes, in modules yes, in ES modules

Packages from npm work in both only if they use no Node-only API. Read more in ES modules and ESM and CommonJS interop.

Security model

This is the most important conceptual difference.

A browser treats code as untrusted. Any website can run JavaScript on your computer, so the browser sandboxes it: no access to your files, cross-site requests restricted by CORS, cookies protected by same-origin rules, permissions for the camera or location.

Node treats code as trusted. A Node program runs with all the permissions of the user who started it. It can read ~/.ssh, delete folders, spawn processes and contact any server. There is no per-script sandbox by default. That power is what makes Node useful, but it means every dependency you install can do anything your program can. Node does have an opt-in permission model (flags such as --permission and --allow-fs-read) for limiting a process; those flags are not available in our editor and are shown read-only:

Terminal
node --permission --allow-fs-read=./data app.mjs

Consequences for you: validate all input, be careful with child_process and file paths built from user data, and review dependencies. See web security.

Also note a networking difference: browser fetch obeys CORS, so a page cannot read most cross-origin responses unless the server allows it. Node's fetch has no CORS restrictions; it can request any URL, so the same-origin policy does not protect a server-side program (a point that matters for server-side request forgery).

Event loop and timers

Both use an event loop, and promises, setTimeout and queueMicrotask behave alike. The details differ a little:

  • Node's timers return a Timeout object; the browser's return a number. Node's object has .unref() (do not keep the process alive for this timer), .ref() and .refresh().
  • Node has setImmediate and process.nextTick, which browsers lack. Browsers have requestAnimationFrame and requestIdleCallback.
  • A browser tab keeps running until closed, but a Node program exits when the loop has no more work. A single setInterval keeps it alive forever unless you clear or unref it.
  • Browsers throttle timers in background tabs; Node does not.
Node.js Timers: object versus number, and unref

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The setInterval would have kept Node running forever, but unref() lets the process exit as soon as the 10 ms timer is done, so "tick" never prints.

Other practical differences

  • No bundler required in Node. Browsers need small, bundled files; Node reads thousands of files from disk happily. Bundling is still used for deployment (see bundling and build).
  • Streams. Node has its own stream module as well as the web ReadableStream; they can be converted. See web streams.
  • Errors. Uncaught errors in a page are logged to the console and the page lives on; in Node an uncaught exception ends the process, so servers handle errors deliberately (error handling in production).
  • Versioning. In a browser you cannot know which engine a visitor has; in Node you pin the version in package.json (engines) or a .nvmrc file.
  • Resources. A Node process can use gigabytes of memory and many CPU cores. A browser tab is limited.

Writing code for both: isomorphic JavaScript

Sometimes the same code must run on the server and in the browser: validation rules shared by form and API, a formatting library, or a framework that renders a page on the server and then continues in the browser. Guidelines:

  1. Keep the core pure. Functions that take values and return values work everywhere. Put anything that touches the DOM, files or sockets into thin adapter layers.
  2. Prefer Web APIs. fetch, URL, TextEncoder, crypto.randomUUID() and structuredClone exist in both. Reaching for node:buffer or node:path ties you to Node.
  3. Detect features, not environments. Ask "does localStorage exist?" rather than "am I in Node?".
  4. Use globalThis, not window or global.
  5. Package conditional exports. A package can publish different entry files per environment through the exports field in package.json. This is a read-only illustration:
JSON
{
  "name": "my-lib",
  "type": "module",
  "exports": {
    ".": {
      "browser": "./dist/browser.js",
      "node": "./dist/node.js",
      "default": "./dist/universal.js"
    }
  }
}

Bundlers pick browser, while Node picks node; the default entry is the fallback. Creating packages covers exports fully.

Node.js A small isomorphic helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The UUID differs on every run, so we print only whether it has the right shape. In a browser the same file would report hasDom: true and hasProcess: false.

Do not share code by blindly importing a server file into front-end code. A single import 'node:fs' in a file that ends up in your browser bundle breaks the build or ships a huge polyfill. Keep server-only modules in clearly named folders, and check what your bundler pulls in.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these works in both Node.js and a browser?

    URL is a web-standard API available in both. The DOM, alert and require('node:fs') belong to only one environment.
  2. 2. Why does document.getElementById('x') fail in Node?

    Node has no DOM. The code throws ReferenceError: document is not defined.
  3. 3. What is a key difference in the security model?

    Browsers sandbox untrusted web code. Node runs trusted code with the user's permissions, so dependencies and inputs need care.
  4. 4. A timer created with setTimeout in Node returns what?

    Node returns a Timeout object. Browsers return a number.
  5. 5. For code that must run in both environments, what is the best guideline?

    Web APIs such as fetch and URL exist in both, and feature detection keeps code portable. window does not exist in Node.

Summary

  • The language and many Web APIs (fetch, URL, AbortController, structuredClone, timers) are shared.
  • Browsers add the DOM, rendering and device APIs; Node adds files, sockets, processes and threads.
  • Node supports ES modules and CommonJS; browsers use ES modules only.
  • Browsers sandbox untrusted code; Node trusts the code it runs, with an optional permission model.
  • Node timers are objects with unref(); Node exits when no work is left and has setImmediate and nextTick.
  • Share code by keeping logic pure, using web-standard APIs, detecting features and using globalThis.

Next: Modern JavaScript You Need