Sub topic 10
Writing Code That Runs Everywhere
This chapter assumes you have read the earlier chapters on ES modules and CommonJS, on asynchronous I/O with promises, and on global objects and environment detection. You should be comfortable writing an ES module, using await, and checking for a global with typeof. The examples need Node.js 20 or later and any current browser.
Universal code is code that runs unchanged in the browser and in Node.js. You can get there in two ways. The first is to restrict yourself to APIs both runtimes share. The second is to isolate the parts that cannot be shared behind a small interface and pick the right implementation when the code is loaded. Most real libraries do both.
The Shared Surface: Web-Standard APIs
Over the last several major releases, Node.js has added many web-standard APIs as globals. The WinterTC group (formerly WinterCG) works to keep this shared set consistent across server runtimes. In practice, code that sticks to these globals and to ES module syntax runs nearly everywhere.
| API | What it does | Global in Node.js since |
|---|---|---|
| `URL`, `URLSearchParams` | Parse and build URLs | 10 |
| `TextEncoder`, `TextDecoder` | Convert between strings and UTF-8 bytes | 11 |
| `queueMicrotask` | Schedule a microtask | 11 |
| `AbortController`, `AbortSignal` | Cancel async operations | 15 |
| `EventTarget`, `Event` | Basic event dispatching | 15 |
| `structuredClone` | Deep-copy values | 17 |
| `fetch`, `Request`, `Response`, `Headers` | HTTP requests | 18 |
| `Blob`, `ReadableStream` | Binary data and web streams | 18 |
| `crypto` (Web Crypto) | Random values, hashing, signing | 19 (behind a flag earlier) |
Some APIs share a name but behave differently. setTimeout exists in both runtimes, but the browser returns a number and Node.js returns a Timeout object. Code that treats the handle as anything other than an opaque value to pass to clearTimeout will break in one of the two.
A universal hashing module
The module below uses only shared APIs. TextEncoder turns the string into bytes, and Web Crypto computes the digest.
{
"name": "universal-demo",
"type": "module"
}// src/hash.js
export async function sha256Hex(text) {
const bytes = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(digest), (b) =>
b.toString(16).padStart(2, '0'),
).join('');
}// main.js (run with: node main.js)
import { sha256Hex } from './src/hash.js';
console.log(await sha256Hex('hello'));
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824The same src/hash.js file loads in a page through <script type="module"> and produces the same output.
Cancellation with AbortSignal
fetch combined with AbortSignal.timeout gives you a timeout that works the same way in both runtimes.
// src/http.js
export async function getJsonWithTimeout(url, ms = 5000) {
try {
const response = await fetch(url, { signal: AbortSignal.timeout(ms) });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Request to ${url} timed out after ${ms} ms`);
}
throw err;
}
}The fetch call looks identical in both runtimes, but the surrounding rules differ. In the browser, a relative URL such as /api/items resolves against the page's address, and cross-origin requests are subject to CORS. Node.js has no page address, so a relative URL throws TypeError: Failed to parse URL, and Node.js does not enforce CORS. A universal function should accept absolute URLs, or take a base URL as a parameter and build the full address with new URL(path, base).
Isolating What Cannot Be Shared
Some work has no shared API. Reading files, saving state, and opening sockets work differently in each runtime. To handle that, split your code into three layers:
- A core of pure logic that uses only shared APIs and receives everything else as parameters.
- Adapters, one per runtime, that implement a small interface with host-specific APIs.
- Entry points that connect an adapter to the core.
The core
The core receives a store object and never checks which runtime it is in.
// src/visits.js
export async function recordVisit(store) {
const count = ((await store.get('visits')) ?? 0) + 1;
await store.set('visits', count);
return count;
}Both adapter methods return promises, even though localStorage is synchronous. If you design the interface around the slowest implementation, the core never has to change.
The adapters
// src/storage.node.js
import { readFile, writeFile } from 'node:fs/promises';
export function createStore(path = './store.json') {
async function load() {
try {
return JSON.parse(await readFile(path, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return {};
throw err;
}
}
return {
async get(key) {
return (await load())[key];
},
async set(key, value) {
const data = await load();
data[key] = value;
await writeFile(path, JSON.stringify(data));
},
};
}// src/storage.browser.js
export function createStore(prefix = 'app:') {
return {
async get(key) {
const raw = localStorage.getItem(prefix + key);
return raw === null ? undefined : JSON.parse(raw);
},
async set(key, value) {
localStorage.setItem(prefix + key, JSON.stringify(value));
},
};
}Choosing the adapter with conditional exports
You could pick an adapter at runtime with if (isNode) await import('node:fs/promises'), but that approach causes trouble. A bundler building for the browser still sees the node:fs/promises specifier, and it will either fail or ship a stub. A better option is to let the module resolver pick the file. The imports field in package.json maps a private specifier starting with # to different files, depending on conditions:
{
"name": "universal-demo",
"type": "module",
"imports": {
"#store": {
"node": "./src/storage.node.js",
"browser": "./src/storage.browser.js",
"default": "./src/storage.browser.js"
}
},
"exports": {
".": "./src/index.js"
}
}// src/index.js
import { createStore } from '#store';
import { recordVisit } from './visits.js';
export { sha256Hex } from './hash.js';
export { getJsonWithTimeout } from './http.js';
export async function visit() {
return recordVisit(createStore());
}// try.js (run with: node try.js, then run it again)
import { visit } from './src/index.js';
console.log('visit number', await visit());Node.js always matches the node condition, so it loads storage.node.js. Bundlers such as Vite, webpack, and esbuild match browser when they build for the web. The resolver checks conditions in the order written, and the first match wins, so default must come last. Plain browsers without a bundler do not read package.json. To use #store in a browser without a bundler, add an import map that points #store to the browser file.
Common Pitfalls
Code often looks universal but contains a hidden dependency on one host. The usual suspects:
Bufferexists only in Node.js. UseUint8Array, whichBuffersubclasses, together withTextEncoderandTextDecoder. Code that receives aBufferfrom Node.js APIs can treat it as aUint8Array.__dirname,__filename, andrequiredo not exist in ES modules in either runtime. Usenew URL('./file', import.meta.url). In Node.js 20.11 and later,import.meta.dirnameis also available, but browsers do not have it.process.envexists only in Node.js. Some bundlers replaceprocess.env.NODE_ENVat build time, but any other access fails in the browser. Pass configuration into your functions as parameters.windowdoes not exist in Node.js or in Web Workers, andselfdoes not exist in Node.js. UseglobalThis.- Node.js streams such as
fs.createReadStreamare not web streams. Convert them withReadable.toWeb()fromnode:streaminside the Node.js adapter, and let the core accept onlyReadableStream. - Error shapes differ. Node.js system errors carry
err.codevalues such asENOENT, while web APIs throwDOMExceptionobjects identified byerr.name. Handle host-specific errors inside the adapter and rethrow something the core understands. - Top-level
awaitworks in ES modules in both runtimes, but a CommonJS module cannotrequirea module that uses it. If you publish a library, avoid top-levelawaitin its entry points.
Testing in Both Runtimes
A module counts as universal only once you have run it in both runtimes. Test the core in Node.js with the built-in test runner, giving it an in-memory store:
// test/visits.test.js (run with: node --test)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { recordVisit } from '../src/visits.js';
function memoryStore() {
const data = new Map();
return {
async get(key) { return data.get(key); },
async set(key, value) { data.set(key, value); },
};
}
test('recordVisit counts up from 1', async () => {
const store = memoryStore();
assert.equal(await recordVisit(store), 1);
assert.equal(await recordVisit(store), 2);
});Then run at least a smoke test in a real browser, either through a browser-based test runner or a small HTML page that imports src/index.js through a bundler's dev server. Linters can also help. ESLint's globals configuration can flag process or document in files meant to be shared.
Exercise
A shared module builds request URLs with fetch('/api/users'). It works in the browser but throws TypeError: Failed to parse URL in Node.js. Explain why and give a universal fix.
Show answer
In the browser, a relative URL resolves against the page's address. Node.js has no page address, so it cannot parse a relative URL. Accept a base URL as a parameter and call fetch(new URL('/api/users', baseUrl)), or require callers to pass absolute URLs.
Exercise
Your package's imports map lists "default": "./src/storage.browser.js" first, followed by "node": "./src/storage.node.js". Which file does Node.js load for #store, and why?
Show answer
Node.js loads storage.browser.js. The resolver checks conditions in the order they appear and stops at the first match, and default always matches. Put default last so that more specific conditions such as node get a chance to match first.
Exercise
A function in your core module returns Buffer.from(text).toString('base64'). Rewrite it so that it runs in both the browser and Node.js 20 using only shared globals.
Show answer
Encode the text to bytes, then base64-encode them with btoa, which both runtimes provide. For example: const bytes = new TextEncoder().encode(text); let bin = ''; for (const b of bytes) bin += String.fromCharCode(b); return btoa(bin);.