Sub topic 10
Writing Code That Runs Everywhere
This chapter assumes you know ES module syntax, async/await, and the differences between window, globalThis, and process that the earlier chapters covered. The goal is a module that runs unchanged in a browser and in Node.js, with no build step and no runtime checks scattered through it.
The working model
Universal code depends only on what both hosts provide: the ECMAScript language itself, plus a growing set of web-standard APIs that Node.js has adopted. Anything specific to one host, such as the DOM, fs, or process, stays at the edges of the program. Small adapter files handle those parts, and the shared core never imports them.
APIs you can rely on
| API | Browser | Node.js |
|---|---|---|
| `fetch`, `Request`, `Response` | Yes | 18 and later |
| `URL`, `URLSearchParams` | Yes | Yes |
| `TextEncoder`, `TextDecoder` | Yes | Yes |
| `AbortController`, `setTimeout` | Yes | Yes |
| `structuredClone` | Yes | 17 and later |
| `crypto.subtle`, `crypto.randomUUID` | Secure contexts only | Global in 19 and later |
| `document`, `localStorage` | Yes | No |
| `fs`, `process`, `Buffer` | No | Yes |
A portable module
This module uses only shared APIs, so it runs in either host:
// hash.mjs
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.mjs (run with: node main.mjs)
import { sha256Hex } from './hash.mjs';
console.log(await sha256Hex('hello'));
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824A browser page can load the same hash.mjs file with <script type="module">. Note that crypto.subtle exists only on HTTPS pages or on localhost.
The same rule applies to network code. The getJson function below works in both hosts because fetch is global in each:
export async function getJson(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
}Inject host-specific behavior
When the core needs something only one host has, such as storage, pass that capability in as a parameter. Don't reach for a global from inside the core.
// counter.mjs (shared core)
export function createCounter(store) {
return {
async increment(key) {
const value = Number((await store.get(key)) ?? 0) + 1;
await store.set(key, String(value));
return value;
},
};
}// node-store.mjs (Node.js adapter)
import { readFile, writeFile } from 'node:fs/promises';
export function fileStore(path) {
return {
async get(key) {
try {
return JSON.parse(await readFile(path, 'utf8'))[key];
} catch {
return undefined;
}
},
async set(key, value) {
let data = {};
try { data = JSON.parse(await readFile(path, 'utf8')); } catch {}
data[key] = value;
await writeFile(path, JSON.stringify(data));
},
};
}A browser adapter would wrap localStorage.getItem and localStorage.setItem behind the same get and set shape. Because the store is passed in, you can also test the core with a plain in-memory object.
Common errors
- Touching a host global at import time. A top-level
window.addEventListener(...)throws aReferenceErroras soon as Node.js imports the file. Move that call into an adapter, or guard it with atypeofcheck. - Using
BufferwhereUint8Arraywould do.Bufferexists only in Node.js.Uint8ArraywithTextEncoderworks in both hosts. - Using
__dirnameorrequire. Neither exists in the browser, and neither exists in Node.js ES modules. To build paths relative to the current module, usenew URL('./file', import.meta.url). - Detecting the environment when you could detect the feature.
if (typeof structuredClone === 'function')tests for the thing you actually need.if (isNode)makes a guess about it instead.
Exercise
This module crashes when Node.js imports it: const lang = navigator.language; export function greet(name) { return lang.startsWith('fr') ? Bonjour ${name} : Hello ${name}; }. Rewrite it so the core is portable.
Show answer
Pass the language in instead of reading it at import time: export function greet(name, lang = 'en') { return lang.startsWith('fr') ? Bonjour ${name} : Hello ${name}; }. The browser caller passes navigator.language. The Node.js caller passes something like Intl.DateTimeFormat().resolvedOptions().locale, which both hosts support.
Exercise
Why is new Uint8Array(await crypto.subtle.digest(...)) a better choice for universal code than Node's createHash from node:crypto?
Show answer
crypto.subtle is a web standard that both hosts provide as a global, so no host-specific import is needed. node:crypto cannot be loaded in a browser.