Questions 41–60 of 200 · 0 of 20 on this page marked learned
41.nodejs-0041Hardsenior
What do keepAliveTimeout, headersTimeout and requestTimeout do on a Node.js HTTP server, and why do they matter?
keepAliveTimeout (default 5 s) closes idle persistent connections. headersTimeout (60 s) limits how long a client may take to send the request headers, and requestTimeout (300 s) limits the whole request. They defend against slow-client attacks and must be tuned relative to the load balancer in front, or you will see random 502 errors.
Full answer
HTTP/1.1 keeps a TCP connection open between requests (keep-alive) so clients avoid a new handshake each time. Without limits, a connection that does nothing, or sends one byte per second, can hold server resources forever. A large number of such connections is the "slowloris" attack.
Main server settings (defaults on current Node):
server.keepAliveTimeout, 5000 ms: how long an idle connection waits for the next request before the server closes it.
server.headersTimeout, 60000 ms: how long the client has to send the complete headers.
server.requestTimeout, 300000 ms: how long the client has to send the whole request, including the body. Slow clients get a 408 response and the connection is closed. The check runs every connectionsCheckingInterval (30 s by default), so the timeout is not exact.
server.timeout, 0 (disabled): inactivity timeout on the socket. Use setTimeout on individual requests for finer control.
server.maxRequestsPerSocket: closes a connection after N requests.
The load balancer problem: suppose a load balancer keeps idle connections to your server for 60 seconds, but your Node server closes idle connections after 5 seconds. Sometimes the balancer sends a request on a connection at the moment Node closes it. The client sees a 502 or a connection reset. The usual rule: set the Node keepAliveTimeout higher than the balancer's idle timeout (for example 65 s against 60 s), and keep headersTimeout above keepAliveTimeout.
Also set limits on header size (--max-http-header-size) and body size, and put timeouts on outgoing requests, since a hanging call to another service ties up your handler.
javascript
const http = require('node:http');
const net = require('node:net');
const defaults = http.createServer();
console.log('default keepAliveTimeout:', defaults.keepAliveTimeout, 'ms');
console.log('default headersTimeout: ', defaults.headersTimeout, 'ms');
console.log('default requestTimeout: ', defaults.requestTimeout, 'ms');
console.log('default timeout: ', defaults.timeout, '(0 means off)');
// A strict server for the demo: the whole request must arrive within 200 ms.
const server = http.createServer(
{ requestTimeout: 200, connectionsCheckingInterval: 50 },
(req, res) => {
req.resume(); // read the body, then answer
req.on('end', () => res.end('ok'));
},
);
server.listen(0, '127.0.0.1', () => {
// A slow client promises 10 body bytes but sends none.
const socket = net.connect(server.address().port, '127.0.0.1', () => {
socket.write('POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: 10\r\n\r\n');
});
let reply = '';
socket.on('data', (chunk) => (reply += chunk));
socket.on('close', () => {
console.log('slow client received:', reply.split('\r\n')[0]);
server.close();
});
});
The demo shortens requestTimeout to 200 ms and the check interval to 50 ms. Production values are far larger. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
default keepAliveTimeout: 5000 ms
default headersTimeout: 60000 ms
default requestTimeout: 300000 ms
default timeout: 0 (0 means off)
slow client received: HTTP/1.1 408 Request Timeout
Key points
keepAliveTimeout closes idle connections, headersTimeout and requestTimeout limit slow requests.
Defaults: 5 s, 60 s and 300 s.
Slow clients can tie up resources, so these limits are a security feature.
Keep Node's keepAliveTimeout above the load balancer idle timeout.
Common mistakes
Leaving a Node server with the 5 second keep-alive behind a load balancer with a 60 second idle timeout.
Disabling all timeouts to 'fix' a slow request instead of finding the cause.
Forgetting timeouts on outgoing HTTP calls.
Assuming requestTimeout fires at exactly the configured millisecond.
Follow-ups
What is a slowloris attack?
How would you debug random 502 errors from a load balancer?
What timeout would you set on an outgoing fetch?
Tips
Give the defaults from memory and say they are tunable.
Explain the load balancer mismatch, because it is a real production bug.
Say that timeouts are a security setting.
42.nodejs-0042Hardsenior
How do you shut down a Node.js HTTP server gracefully on SIGTERM?
On SIGTERM, stop accepting new connections with server.close(), let in-flight requests finish, close idle keep-alive connections, close other resources (database, queues), and exit. Add a forced exit timer in case something hangs. Orchestrators send SIGTERM first and SIGKILL after a grace period.
Full answer
When you deploy or scale down, the platform sends SIGTERM to the process. If the process dies at once, requests in progress fail. A graceful shutdown avoids lost work.
Sequence:
Handle SIGTERM (and SIGINT for Ctrl+C): process.once('SIGTERM', shutdown).
Mark the app as not ready. A health check endpoint should now fail, so the load balancer stops sending traffic.
server.close(): stops accepting new connections. The callback runs when all connections have ended. Since Node 19, server.close() also closes idle keep-alive connections. server.closeIdleConnections() does that explicitly, and server.closeAllConnections() cuts everything, as a last resort.
Wait for in-flight requests to complete.
Close the rest: database pools, message queue consumers, timers. Flush logs.
Exit with code 0. Set a deadline (for example 10 s, shorter than the platform grace period) after which you call process.exit(1). Call .unref() on that timer so it does not keep the process alive by itself.
Keep-alive connections are the usual reason shutdown hangs: an idle connection never ends by itself, so close() waits for the keepAliveTimeout.
Long-lived connections (WebSockets, server-sent events) need an explicit message to clients and a close. Do not forget background jobs: finish or hand back the job in progress.
javascript
const http = require('node:http');
const server = http.createServer((req, res) => {
res.on('finish', () => console.log('3. in-flight request finished normally'));
setTimeout(() => res.end('order saved'), 300); // a slow request
});
let shuttingDown = false;
function shutdown(signal) {
if (shuttingDown) return;
shuttingDown = true;
console.log('2. received', signal, '- no new connections, finishing current requests');
const deadline = setTimeout(() => {
console.log('deadline hit, forcing exit');
process.exit(1);
}, 5000);
deadline.unref(); // the timer alone must not keep the process alive
server.close(() => {
console.log('4. server closed, releasing other resources (database, queues)');
// the process now exits by itself because nothing is left to do
});
server.closeIdleConnections();
}
process.once('SIGTERM', shutdown);
server.listen(0, '127.0.0.1', async () => {
const url = 'http://127.0.0.1:' + server.address().port;
const pending = fetch(url).then((r) => r.text());
setTimeout(() => process.kill(process.pid, 'SIGTERM'), 50); // the platform sends the signal
console.log('1. request started');
await pending;
});
The script sends itself SIGTERM while a request is in progress. The request still completes, and the process exits without a forced kill. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. request started
2. received SIGTERM - no new connections, finishing current requests
3. in-flight request finished normally
4. server closed, releasing other resources (database, queues)
Key points
Handle SIGTERM, stop accepting new work, finish current work, exit.
server.close waits for connections to end. Close idle ones.
Fail the health check first so traffic stops.
Use a deadline timer that is unref'd.
Close databases and queues after the HTTP server.
Common mistakes
Calling process.exit() inside the SIGTERM handler.
Forgetting idle keep-alive connections, so close() waits for many seconds.
Closing the database before the in-flight requests have finished.
Setting a shutdown deadline longer than the platform grace period.
Follow-ups
How does Kubernetes use readiness probes during shutdown?
How would you close WebSocket connections?
What is the difference between SIGTERM, SIGINT and SIGKILL?
Tips
Number the steps. Interviewers like ordered answers.
Mention the health check change, since it is often forgotten.
Say SIGKILL cannot be handled.
43.nodejs-0043Mediummid
What are the common causes of memory leaks in Node.js, and how do you find one?
A leak is memory that the program no longer needs but still references, so garbage collection cannot free it. Common causes are unbounded caches, growing arrays or maps, listeners that are never removed, timers that are never cleared, and closures that capture large objects. Find them by watching heapUsed after GC over time and comparing heap snapshots.
Full answer
V8 frees an object when nothing reachable refers to it. A leak is an object you forgot that you still refer to.
Typical causes:
Unbounded caches: a Map or plain object keyed by user, URL or request id that only grows. Fix with a size limit (LRU), a time limit (TTL), or a WeakMap if keys are objects.
Global arrays used as logs or queues that are never trimmed.
Event listeners added per request and never removed (see MaxListenersExceededWarning).
Timers: setInterval callbacks that are never cleared keep their closure alive.
Closures that capture a large variable although they only need a small part of it.
Promises that never settle and hold their callbacks.
Native memory: Buffers, streams not destroyed, unclosed sockets or file handles (these show up as rss and external, not as heapUsed).
How to find them:
Watch process.memoryUsage(): a leak shows as a steady staircase in heapUsed after garbage collection, and rss rising. A sawtooth that returns to the same low level is healthy.
Take heap snapshots with node --inspect and Chrome DevTools, or v8.writeHeapSnapshot(). Take one, run load, take another, and compare. Look at the objects with growing counts and the retaining path (what holds them).
Use allocation sampling and the --heapsnapshot-signal option on a live process.
Load test a staging copy with a fixed request mix, and see whether memory settles.
A high memory number alone is not a leak. Node may keep memory it can reuse. Check the trend after forced GC.
javascript
const v8 = require('node:v8');
const vm = require('node:vm');
// Allow forced garbage collection without starting node with --expose-gc.
v8.setFlagsFromString('--expose-gc');
const gc = vm.runInNewContext('gc');
const heapMB = () => {
gc();
return process.memoryUsage().heapUsed / 1024 / 1024;
};
// 1. Unbounded cache: every request adds an entry and nothing removes it.
const leakyCache = new Map();
function handleLeaky(requestId) {
leakyCache.set(requestId, new Array(50_000).fill(requestId)); // about 0.4 MB each
}
// 2. Bounded cache: keeps only the 5 newest entries.
const boundedCache = new Map();
function handleBounded(requestId) {
boundedCache.set(requestId, new Array(50_000).fill(requestId));
if (boundedCache.size > 5) boundedCache.delete(boundedCache.keys().next().value);
}
const start = heapMB();
for (let i = 0; i < 200; i++) handleLeaky(i);
const afterLeaky = heapMB();
console.log('leaky cache entries:', leakyCache.size, '| heap grew by more than 40 MB:', afterLeaky - start > 40);
leakyCache.clear();
for (let i = 0; i < 200; i++) handleBounded(i);
const afterBounded = heapMB();
console.log('bounded cache entries:', boundedCache.size, '| heap grew by less than 10 MB:', afterBounded - start < 10);
The snippet forces garbage collection before each measurement, so the comparison does not depend on when the collector happens to run. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
leaky cache entries: 200 | heap grew by more than 40 MB: true
bounded cache entries: 5 | heap grew by less than 10 MB: true
Look at heapUsed after GC over time, not at one number.
Compare heap snapshots to see the retaining path.
Common mistakes
Treating high rss as proof of a leak.
Using a plain object as a cache with no limit.
Adding a setInterval in a request handler.
Taking one heap snapshot and expecting it to show a leak.
Follow-ups
How does a WeakMap help with caches?
What does the retaining path in a heap snapshot tell you?
How do you find a native memory leak that does not show in the heap?
Tips
Say 'reachable but unused' to define a leak.
Describe the two-snapshot method, since it shows practical skill.
Name bounded caches as the first thing to fix.
44.nodejs-0044Hardsenior
How do you find performance problems in a Node.js application: CPU profiling, event loop delay and perf_hooks?
Measure first. Use node --cpu-prof or --inspect to record where CPU time goes, perf_hooks.monitorEventLoopDelay to see how long the loop is blocked, and performance.mark and measure for timing specific code. Then fix the biggest cost and measure again.
Full answer
Guessing about speed is usually wrong. A repeatable method:
Define the symptom: high latency at the 95th percentile, high CPU, or memory growth.
Measure at the right level.
Tools:
Event loop delay: perf_hooks.monitorEventLoopDelay({ resolution: 10 }) records how late a timer fires. A max or p99 above 100 ms means something blocks the loop. This is the best single health number for a Node server.
CPU profile: node --cpu-prof app.js writes a .cpuprofile file. Open it in Chrome DevTools or VS Code. A flame graph shows which functions use the most self time. node --inspect lets you attach and record on a running process. Tools such as 0x and clinic.js build flame graphs from the same data.
Timing code: performance.now(), performance.mark and performance.measure give high-resolution timings, and performance.timerify wraps a function and reports its duration.
Tracing: --trace-gc shows garbage collection pauses, and the diagnostics_channel module gives hooks for HTTP and database events in libraries.
Under load: use autocannon or k6, because single requests hide contention.
Typical fixes: remove synchronous calls, avoid repeated JSON parse and stringify, cache results, batch database queries, stream large payloads, move CPU work to workers, and reduce garbage by reusing objects in hot paths.
Always measure again after a change, with the same load, and keep the number.
javascript
const { monitorEventLoopDelay, performance, PerformanceObserver } = require('node:perf_hooks');
const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();
function slowTask() {
const end = performance.now() + 120;
while (performance.now() < end) { /* block the event loop for 120 ms */ }
}
// Time a block of code with marks and measures.
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('measure', JSON.stringify(entry.name), 'took at least 100 ms:', entry.duration >= 100);
}
});
observer.observe({ entryTypes: ['measure'] });
setTimeout(() => {
performance.mark('start');
slowTask();
performance.mark('end');
performance.measure('slow task', 'start', 'end');
// Give the histogram a turn of the loop to record the delay.
setTimeout(() => {
histogram.disable();
console.log('event loop delay max is above 100 ms:', histogram.max / 1e6 > 100);
console.log('histogram has samples:', histogram.count > 0);
observer.disconnect();
}, 50);
}, 100);
The delay histogram reports nanoseconds, so the code divides by one million to get milliseconds. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
measure "slow task" took at least 100 ms: true
event loop delay max is above 100 ms: true
histogram has samples: true
Key points
Measure before changing anything.
Event loop delay is the key health metric.
--cpu-prof and flame graphs show hot functions.
perf_hooks gives timing marks and measurements.
Test under load and compare before and after.
Common mistakes
Optimising code without a profile.
Looking at average latency only, instead of p95 and p99.
Profiling a debug build or an idle process.
Measuring a single request instead of a load test.
Follow-ups
What is the difference between self time and total time in a flame graph?
How would you profile a production process safely?
How do you measure GC pauses?
Tips
Describe the loop: symptom, measure, fix, measure again.
Name event loop delay as the first metric for a Node server.
Mention percentile latency, not averages.
45.nodejs-0045Mediummid
How do you run many async tasks in parallel with a fixed limit, for example 3 at a time?
Start a fixed number of runners. Each runner takes the next task from a shared index, awaits it, and then takes another until the list is empty. This keeps at most N tasks active, preserves result order, and avoids both slow sequential loops and unlimited Promise.all.
Full answer
Two extremes are both bad for 10,000 API calls or file operations:
Sequential await in a loop: safe but slow, because nothing overlaps.
Promise.all over everything: starts all tasks at once. That can exhaust file descriptors (EMFILE), crush a database or trigger rate limits, and uses a lot of memory.
The balanced approach is a concurrency limit. A simple and correct pattern:
Keep an index of the next task to run.
Start N runner functions. Each runner loops: take the next index, run the task, store the result at that index, repeat until no tasks remain.
await Promise.all(runners).
Because JavaScript is single-threaded, taking the next index (i++) is safe with no lock. Storing the result at the same index keeps the order of the output the same as the input.
Error policy needs a decision: fail fast (the first rejection stops new tasks) or collect errors per item (like allSettled). Retry with backoff for temporary failures.
Libraries such as p-limit, p-map and Node's own stream helpers (readable.map(fn, { concurrency })) do this. Use a library in production, but write the loop once so you understand it.
Choose N from the resource you protect: database pool size, API rate limit, or CPU count.
javascript
async function mapLimit(items, limit, task) {
const results = new Array(items.length);
let next = 0;
async function runner() {
while (next < items.length) {
const index = next++; // safe: JavaScript runs one callback at a time
results[index] = await task(items[index], index);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, runner));
return results;
}
// A pretend API call that takes a different time per item.
const fakeFetch = (id) => new Promise((resolve) => setTimeout(() => resolve('student-' + id), (id % 4) * 5 + 5));
async function main() {
let active = 0;
let maxActive = 0;
const ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const results = await mapLimit(ids, 3, async (id) => {
active++;
maxActive = Math.max(maxActive, active);
const value = await fakeFetch(id);
active--;
return value;
});
console.log('results in input order:', results.join(', '));
console.log('most tasks active at once:', maxActive);
}
main();
Different delays per task mean they finish out of order, yet the output list keeps the input order. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
results in input order: student-1, student-2, student-3, student-4, student-5, student-6, student-7, student-8, student-9, student-10
most tasks active at once: 3
Key points
Limit concurrency to protect resources.
N runners pulling from a shared index is enough.
Writing results by index keeps the order.
Decide how errors are handled before you write the code.
Common mistakes
Using Promise.all(items.map(task)) for thousands of items.
Using array.forEach(async ...) and expecting the code to wait.
Awaiting inside a for loop for independent tasks.
Not deciding what happens when one task fails.
Follow-ups
How would you add retry with exponential backoff?
How do Node streams offer a concurrency option?
How do you cancel pending tasks when one fails?
Tips
Name the three options: sequential, unlimited, limited.
Explain why i++ is safe without a lock.
Mention p-limit as the library you would normally use.
46.nodejs-0046Hardsenior
What is a cache stampede, and how do you prevent it by caching promises?
A cache stampede happens when many requests ask for the same missing or expired item at once, and each one calls the slow backend. Store the in-flight promise in the cache, so the first caller starts the work and all other callers await the same promise. Remove failed promises and use a TTL.
Full answer
Suppose a dashboard value is cached for 60 seconds and takes 2 seconds to compute. At the moment it expires, 500 requests arrive. Each sees an empty cache and starts its own 2-second computation. The backend gets 500 heavy calls at once, slows down, and the response time grows, which invites more calls.
The fix in Node is simple because of the single thread. Cache the promise, not only the value:
On a request, look up the key.
If a promise exists (finished or still running), return it.
If not, call the loader function, store the returned promise immediately (before any await), and return it.
If the promise rejects, delete the key so the next call can retry. Otherwise the failure is cached.
Add an expiry (TTL). A common refinement is stale-while-revalidate: serve the old value while one background refresh runs.
This works inside one process. With several processes or servers you still get one call per process. For a stronger guarantee use a shared cache with a lock or a short-lived "refresh in progress" key (for example in Redis), and add random jitter to expiry times so all keys do not expire together.
Limit the cache size too, or the cache itself becomes a memory leak.
javascript
function createCache(loader, ttlMs) {
const entries = new Map(); // key -> { promise, expires }
return function get(key) {
const entry = entries.get(key);
if (entry && entry.expires > Date.now()) return entry.promise;
const promise = loader(key); // start the work and store the promise at once
entries.set(key, { promise, expires: Date.now() + ttlMs });
promise.catch(() => {
if (entries.get(key)?.promise === promise) entries.delete(key); // do not cache failures
});
return promise;
};
}
async function main() {
let backendCalls = 0;
const slowBackend = (id) =>
new Promise((resolve) => setTimeout(() => { backendCalls++; resolve({ id, average: 74.5 }); }, 50));
const get = createCache(slowBackend, 1000);
const requests = Array.from({ length: 100 }, () => get('class-10A'));
const answers = await Promise.all(requests);
console.log('requests:', requests.length, '| backend calls:', backendCalls);
console.log('all callers got the same object:', answers.every((a) => a === answers[0]));
// A failing loader is not cached.
let attempts = 0;
const flaky = createCache(async () => {
attempts++;
if (attempts === 1) throw new Error('backend busy');
return 'ok on attempt ' + attempts;
}, 1000);
await flaky('x').catch((e) => console.log('first call failed:', e.message));
await new Promise((r) => setImmediate(r)); // let the clean-up run
console.log('second call:', await flaky('x'));
}
main();
One hundred simultaneous callers cause a single backend call. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
requests: 100 | backend calls: 1
all callers got the same object: true
first call failed: backend busy
second call: ok on attempt 2
Key points
Many callers for the same missing key overload the backend.
Store the promise at once so later callers share it.
Delete rejected promises.
Use TTL, jitter and stale-while-revalidate.
Per-process only. Use a shared lock across servers.
Common mistakes
Caching the resolved value only, so the work starts again for every parallel request.
Caching a rejected promise for the full TTL.
Letting all keys expire at the same second.
Growing the cache without a size limit.
Follow-ups
How would you share the lock across several servers?
How does stale-while-revalidate change user latency?
How would you add a maximum size to this cache?
Tips
Start with the 500-requests picture.
Explain why storing the promise before any await is the key step.
Mention jitter to show you know the multi-server case.
47.nodejs-0047Easyfresher
How do you prevent SQL injection and command injection in Node.js?
Injection happens when untrusted text is mixed into a command that is then interpreted. Use parameterized queries so values are sent separately from SQL, and use execFile or spawn with an argument array instead of exec with a string. Also validate input and give database accounts minimum rights.
Full answer
Injection means attacker-controlled text changes the meaning of a command.
SQL injection. If you build SQL with a template string, input such as ' OR '1'='1 turns a filter into "always true" and returns every row. The fix is a parameterized query (prepared statement): the SQL text has placeholders (?, $1), and the driver sends values separately. The database never parses the values as SQL. This works the same in sqlite, pg, mysql2 and ORMs. Identifiers (table and column names) cannot be parameters, so choose them from a fixed allow-list.
Command injection. child_process.exec(ls ${folder}) runs the whole string in a shell. A value such as x; rm -rf ~ runs a second command. Use execFile('ls', [folder]) or spawn, which pass each argument directly with no shell. Even then, check that a value cannot start with - and be read as an option; the -- marker helps.
Other injection places: NoSQL (an object like { "$ne": null } where a string was expected), template engines, regular expressions built from input, log lines (new line characters), and HTTP headers.
Defence in depth: validate type, length and format; use least privilege database users (no DROP rights for the web app); and never show raw database errors to users.
javascript
const { DatabaseSync } = require('node:sqlite');
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const db = new DatabaseSync(':memory:');
db.exec(`
CREATE TABLE students (name TEXT, marks INTEGER, private_note TEXT);
INSERT INTO students VALUES ('Asha', 78, 'scholarship file'), ('Ravi', 91, 'counselling file');
`);
const attack = "x' OR '1'='1";
// Unsafe: the input becomes part of the SQL text.
const unsafe = db.prepare(`SELECT name FROM students WHERE name = '${attack}'`).all();
console.log('unsafe query returned rows:', unsafe.length);
// Safe: the input is sent as a value.
const safe = db.prepare('SELECT name FROM students WHERE name = ?').all(attack);
console.log('parameterized query returned rows:', safe.length);
// Command injection: exec-style strings vs argument arrays.
(async () => {
const hostile = 'hello; echo INJECTED';
const { stdout } = await promisify(execFile)(process.execPath, ['-p', 'process.argv[1]', hostile]);
console.log('execFile treats the whole text as one argument:', JSON.stringify(stdout.trim()));
})();
This example uses the sqlite module that ships with Node.js 22 and later, so it needs no install. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
unsafe query returned rows: 2
parameterized query returned rows: 0
execFile treats the whole text as one argument: "hello; echo INJECTED"
Key points
Keep data and commands separate.
Parameterized queries for SQL.
execFile or spawn with an array, not exec with a string.
Validate input and limit database privileges.
Common mistakes
Building SQL with template strings.
Escaping quotes by hand instead of using placeholders.
Using exec with user input.
Using the database admin account for the web app.
Follow-ups
Why can table names not be parameters?
How does NoSQL injection work in a MongoDB filter?
What is the purpose of the -- argument separator?
Tips
Say 'data and code stay separate' in one sentence.
Show the attack string and what it does.
Mention least privilege to show defence in depth.
48.nodejs-0048Hardsenior
What is prototype pollution, and how do you defend a Node.js application against it?
Prototype pollution is when an attacker sets properties on Object.prototype, usually through keys like __proto__ in input that a function merges or copies recursively. Every object then inherits the attacker's value, which can change logic or lead to remote code execution. Defend by validating input, skipping dangerous keys, and using Object.create(null) or Map.
Full answer
Almost every JavaScript object inherits from Object.prototype. If code writes to Object.prototype, every object that does not define that property itself will see the value.
How attackers get there: a recursive merge, clone or "set by path" function walks the keys of user JSON. The JSON {"proto": {"isAdmin": true}} is parsed by JSON.parse as an object with an own property named proto. A naive merge then does target['proto']['isAdmin'] = true, and target['proto'] is the real Object.prototype. After that, ({}).isAdmin is true everywhere in the process. Query strings with a[proto][x]=1 and paths such as constructor.prototype lead to the same problem.
Impact: authorization bypass (if (user.isAdmin)), denial of service, and in some template or child_process option patterns, remote code execution.
Defences:
Validate input with a schema that rejects unknown keys.
In merge code, skip proto, constructor and prototype, or only copy own properties with Object.hasOwn.
Use Object.create(null) for dictionaries, or Map, which have no inherited keys.
Use maintained libraries and update them. Most past vulnerabilities were in merge, clone and query-string packages.
Freeze the prototype at start-up (Object.freeze(Object.prototype)) or run with node --disable-proto=delete. Test that your dependencies still work.
Check privileges with an own property or a Set of IDs, not with a plain truthy lookup on an object that can inherit.
javascript
const input = JSON.parse('{"theme": "dark", "__proto__": {"isAdmin": true}}');
function unsafeMerge(target, source) {
for (const key of Object.keys(source)) {
if (typeof source[key] === 'object' && source[key] !== null) {
if (typeof target[key] !== 'object' || target[key] === null) target[key] = {};
unsafeMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
function safeMerge(target, source) {
for (const key of Object.keys(source)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
if (typeof source[key] === 'object' && source[key] !== null) {
if (!Object.hasOwn(target, key) || typeof target[key] !== 'object') target[key] = {};
safeMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
const user = {};
console.log('before: a new object has isAdmin:', ({}).isAdmin);
safeMerge({}, input);
console.log('after safeMerge: a new object has isAdmin:', ({}).isAdmin);
unsafeMerge({}, input); // (error on purpose) the vulnerable version
console.log('after unsafeMerge: a new object has isAdmin:', ({}).isAdmin);
console.log('an unrelated user object is now admin:', user.isAdmin === true);
// A dictionary without a prototype cannot be polluted this way.
const safeDictionary = Object.create(null);
console.log('null-prototype object has isAdmin:', safeDictionary.isAdmin);
The unsafe merge is the deliberate bug (error on purpose). After it runs, every object in the process inherits isAdmin. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
before: a new object has isAdmin: undefined
after safeMerge: a new object has isAdmin: undefined
after unsafeMerge: a new object has isAdmin: true
an unrelated user object is now admin: true
null-prototype object has isAdmin: undefined
Key points
JSON.parse creates an own '__proto__' key that merge code may follow into Object.prototype.
Everything inherits the polluted property.
Skip dangerous keys, validate input, use Map or null-prototype objects.
--disable-proto=delete and freezing add defence in depth.
Common mistakes
Using a hand-written deep merge on user input.
Checking permissions with if (obj.isAdmin) on an object built from user data.
Believing JSON.parse itself pollutes the prototype. The merge does.
Ignoring the problem in dependencies such as old lodash or query parsers.
Follow-ups
How does Object.hasOwn differ from the in operator?
What is the difference between __proto__ and prototype?
How can prototype pollution lead to remote code execution?
Tips
Walk through the attack in three lines: JSON, merge, inheritance.
Offer both prevention (validation) and mitigation (freeze, flags).
Say that outdated dependencies are the usual source.
49.nodejs-0049Mediummid
How do you prevent path traversal when serving files based on user input?
Path traversal uses segments like ../ to leave the intended folder. Resolve the final absolute path with path.resolve, then check that it still starts with the base directory plus a path separator. Reject null bytes, and use fs.realpath if symbolic links are possible.
Full answer
Suppose a route serves files from /srv/public/<name>. A request for ../../etc/passwd becomes /srv/public/../../etc/passwd, which the operating system resolves to /etc/passwd. The same issue appears in downloads, uploads (filenames), zip extraction ("zip slip") and template includes.
Defence steps:
Decode the input once (URL decoding happens first, then check).
Build the absolute path with path.resolve(base, userPart). Resolve removes ../ segments.
Compare: the result must start with base + path.sep. Checking only startsWith(base) is not enough, because /srv/public-secret starts with /srv/public.
Reject names containing a null byte, and consider allowing only a pattern such as [a-z0-9._-]+ when the use case allows it.
Resolve symbolic links with fs.realpath and compare again, otherwise a link inside the folder can point outside it.
Run the process with least privilege, so a mistake cannot read secrets. Prefer an allow-list (file ids in a database) over file names from the URL.
Do not rely on path.normalize or path.join alone. They tidy the path but do not keep it inside a folder.
A production static file server (serve-static, a CDN, nginx) already does these checks. Write your own only when you have to, and test it with encoded values such as %2e%2e%2f.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'web-'));
const base = path.join(root, 'public');
fs.mkdirSync(base);
fs.mkdirSync(path.join(root, 'public-secret'));
fs.writeFileSync(path.join(base, 'notes.txt'), 'public notes');
fs.writeFileSync(path.join(root, 'public-secret', 'keys.txt'), 'secret');
function resolveSafe(userPart) {
if (userPart.includes('\0')) return null;
const full = path.resolve(base, userPart);
return full.startsWith(base + path.sep) ? full : null;
}
function weakCheck(userPart) {
const full = path.resolve(base, userPart);
return full.startsWith(base) ? full : null; // missing the separator
}
for (const name of ['notes.txt', '../package.json', '../../etc/passwd', '../public-secret/keys.txt']) {
console.log(name.padEnd(28), 'safe:', resolveSafe(name) !== null, '| weak check:', weakCheck(name) !== null);
}
fs.rmSync(root, { recursive: true });
The weak check accepts a sibling folder whose name starts with the same text as the base folder, which is the classic mistake. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
notes.txt safe: true | weak check: true
../package.json safe: false | weak check: false
../../etc/passwd safe: false | weak check: false
../public-secret/keys.txt safe: false | weak check: true
Key points
../ segments can leave the base folder.
Resolve first, then compare with base plus path.sep.
Check symlinks with realpath.
Prefer allow-lists and tested libraries.
Common mistakes
Using path.join(base, input) and reading the result directly.
Checking startsWith(base) without the separator.
Ignoring symbolic links and archive extraction.
Checking the path before URL decoding.
Follow-ups
What is the 'zip slip' vulnerability?
How would you serve user uploads safely?
How do you test for traversal attacks?
Tips
Show the sibling folder trap. It proves attention to detail.
Prefer IDs over file names, and say why.
Name realpath for the symlink case.
50.nodejs-0050Mediummid
How should a Node.js application store passwords and compare secrets safely?
Never store passwords in plain text or with a fast hash. Use a slow, salted password hash such as scrypt (built into Node), argon2 or bcrypt, store the salt and parameters with the hash, and compare with crypto.timingSafeEqual. Keep secrets in environment variables or a secret manager, not in source code.
Full answer
A fast hash such as SHA-256 lets an attacker who steals the database test billions of guesses per second. Password hashing functions are slow and memory-hungry on purpose, and they use a random salt, so equal passwords give different hashes and precomputed tables (rainbow tables) are useless.
Node has crypto.scrypt built in. Steps:
Create a random salt of at least 16 bytes with crypto.randomBytes.
Derive a key with scrypt(password, salt, 64). The async version uses the libuv thread pool, so it does not block the event loop (the sync version does).
Store algorithm, parameters, salt and hash together, for example scrypt$N$salt$hash, so you can change the settings later and re-hash on login.
To check a login, derive the key with the stored salt and compare using crypto.timingSafeEqual. A normal === comparison stops at the first different byte, and response time can leak how many bytes matched. timingSafeEqual takes the same time for equal-length inputs and throws if the lengths differ, so compare lengths first.
Related rules:
Use crypto.randomBytes or crypto.randomUUID for tokens. Math.random is predictable.
Do not put secrets in source code, logs or client bundles. Read them from process.env, or a secret manager, and rotate them.
Rate-limit login attempts and use multi-factor authentication for important accounts.
Because scrypt uses the thread pool, a flood of logins can saturate it. Limit the concurrency.
The default scrypt cost is acceptable for learning. For production, follow current guidance for the cost parameters and test the time per hash on your hardware. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
stored format has 3 parts: true
same password, different hashes: true
correct password accepted: true
wrong password rejected: true
random token length (43 chars for 32 bytes): 43
Key points
Slow, salted hashes: scrypt, argon2 or bcrypt.
Store salt and parameters with the hash.
Compare with timingSafeEqual.
Use randomBytes for tokens, never Math.random.
Keep secrets out of code and logs.
Common mistakes
Hashing passwords with SHA-256 or MD5.
Using one global salt for all users.
Comparing hashes with ===.
Using Math.random for reset tokens.
Follow-ups
How would you upgrade the cost parameters later without forcing a reset?
Why is the async scrypt better than the sync version in a server?
How do you protect against credential stuffing?
Tips
Explain salt and slowness in one sentence each.
Mention timing attacks, because it separates good answers from average ones.
State that tokens come from a cryptographic random source.
51.nodejs-0051Easyfresher
How do util.promisify and util.callbackify work, and when does promisify give the wrong result?
util.promisify turns a function that takes an error-first callback as its last argument into a function that returns a promise. util.callbackify does the reverse. promisify gives a wrong result for functions whose callback does not follow the (err, value) rule, unless the function defines util.promisify.custom.
Full answer
Older Node APIs and many libraries use the callback style: the last argument is a function called with (err, result). Modern code prefers promises, because they work with async/await and try/catch.
util.promisify(fn) wraps such a function:
It calls fn with all the arguments you pass, plus its own callback as the last argument.
If the callback gets a truthy first argument, the promise rejects with it.
Otherwise the promise resolves with the second argument.
util.callbackify(asyncFn) does the opposite, which helps when old code must call new code. One detail: if the promise rejects with a falsy value (null, 0, ''), callbackify wraps it in an Error, because a falsy first argument would mean success.
When promisify goes wrong:
A callback that does not use (err, value). Example: a legacy function that calls cb(true) for "yes". promisify treats true as an error and rejects.
A callback with several result values, such as cb(null, a, b). Only the first result is kept.
Methods that use this. Pass a bound function: promisify(obj.method.bind(obj)).
The fix for odd callbacks is util.promisify.custom, a symbol property that holds the promise-returning version. Core functions use it: promisify(setTimeout) returns a function (delay, value) that resolves with value after the delay. Many core modules also ship promise APIs already (fs/promises, timers/promises, dns/promises, stream/promises), so check before wrapping.
javascript
const { promisify, callbackify } = require('node:util');
// A normal error-first callback function.
function getMarks(student, callback) {
setTimeout(() => {
if (student === 'unknown') return callback(new Error('no such student'));
callback(null, { student, marks: 82 });
}, 5);
}
const getMarksAsync = promisify(getMarks);
// A legacy function with a non-standard callback: cb(true) means "open".
function isOpen(callback) {
setImmediate(() => callback(true));
}
// Give promisify the right translation.
function isOpenWithCustom(callback) {
setImmediate(() => callback(true));
}
isOpenWithCustom[promisify.custom] = () => new Promise((resolve) => isOpenWithCustom(resolve));
async function main() {
console.log('resolved:', await getMarksAsync('Asha'));
await getMarksAsync('unknown').catch((err) => console.log('rejected:', err.message));
// promisify(setTimeout) is built in through promisify.custom: (delay, value)
console.log('setTimeout value:', await promisify(setTimeout)(5, 'done waiting'));
// The wrong translation: true is treated as an error.
await promisify(isOpen)().catch((value) => console.log('plain promisify rejected with:', value));
console.log('with promisify.custom:', await promisify(isOpenWithCustom)());
// callbackify: promise function -> callback function
const double = async (n) => n * 2;
await new Promise((resolve) => {
callbackify(double)(21, (err, result) => {
console.log('callbackify result:', err, result);
resolve();
});
});
}
main();
The isOpen example is the trap: the callback sends true as the first argument, so plain promisify rejects instead of resolving. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
resolved: { student: 'Asha', marks: 82 }
rejected: no such student
setTimeout value: done waiting
plain promisify rejected with: true
with promisify.custom: true
callbackify result: null 42
Key points
promisify expects (err, value) callbacks as the last argument.
callbackify goes from promise to callback.
Non-standard callbacks need util.promisify.custom.
Prefer built-in promise APIs when they exist.
Common mistakes
Promisifying a method and losing this.
Promisifying a function whose callback is not error-first.
Wrapping fs functions when fs/promises already exists.
Ignoring that only the first result value is kept.
Follow-ups
How would you promisify a function that returns two values?
What does util.promisify.custom do on setTimeout?
When would you use callbackify in new code?
Tips
Name the error-first rule before anything else.
Show the cb(true) trap. It proves you read the rules, not only the headline.
Mention that most core modules already have promise versions.
52.nodejs-0052Mediummid
How do AbortController and AbortSignal work in Node.js, and how do you use them for timeouts and cancellation?
An AbortController owns a signal. Calling controller.abort() marks the signal as aborted and fires an abort event. APIs that accept a signal (fetch, timers/promises, fs, events, streams, child_process) stop and reject with an AbortError. AbortSignal.timeout(ms) gives a signal that aborts by itself, and AbortSignal.any combines signals.
Full answer
Promises cannot be cancelled by themselves. AbortController is the standard way to say "stop this work".
Parts:
controller = new AbortController() and controller.signal.
controller.abort(reason) sets signal.aborted to true, sets signal.reason (an AbortError by default), and fires the 'abort' event once.
AbortSignal.timeout(ms) returns a signal that aborts after ms with a TimeoutError. The timer does not keep the process alive.
AbortSignal.any([a, b]) aborts when any of the signals aborts, which is good for "user cancelled or 5 seconds passed".
signal.throwIfAborted() throws the reason when called after an abort.
Where Node accepts a signal: fetch, fs.promises.readFile and writeFile, timers/promises, events.once and events.on, stream.pipeline, child_process.spawn, http.request, readline and worker setup. The call stops its work and rejects with an error whose name is AbortError (or TimeoutError for timeouts).
Supporting a signal in your own function: check signal.aborted before starting, listen with signal.addEventListener('abort', handler, { once: true }), stop the real work in the handler, and remove the listener when finished.
Typical uses: request timeouts, cancelling work when a client disconnects, stopping background loops during shutdown, and cleaning up in tests.
An aborted signal stays aborted. Create a new controller for each operation.
javascript
const http = require('node:http');
const { setTimeout: sleep } = require('node:timers/promises');
// Your own function that supports cancellation.
async function slowJob(ms, { signal } = {}) {
signal?.throwIfAborted();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve('job finished'); }, ms);
const onAbort = () => { clearTimeout(timer); reject(signal.reason); };
signal?.addEventListener('abort', onAbort, { once: true });
});
}
async function main() {
// A server that answers after 200 ms.
const server = http.createServer((req, res) => setTimeout(() => res.end('late answer'), 200));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = 'http://127.0.0.1:' + server.address().port;
// 1. fetch with a timeout signal
await fetch(url, { signal: AbortSignal.timeout(50) }).catch((err) => console.log('fetch timeout ->', err.name));
// 2. manual abort with a custom reason
const controller = new AbortController();
setTimeout(() => controller.abort(new Error('user pressed cancel')), 20);
await fetch(url, { signal: controller.signal }).catch((err) => console.log('manual abort ->', err.name + ':', err.message));
// 3. timers/promises accept a signal too
const c2 = new AbortController();
const waiting = sleep(1000, 'never used', { signal: c2.signal });
c2.abort();
await waiting.catch((err) => console.log('sleep aborted ->', err.name));
// 4. our own function, plus AbortSignal.any
const user = new AbortController();
const combined = AbortSignal.any([user.signal, AbortSignal.timeout(30)]);
await slowJob(500, { signal: combined }).catch((err) => console.log('slowJob stopped by ->', err.name));
console.log('slowJob without a signal:', await slowJob(5));
console.log('user signal aborted:', user.signal.aborted, '| combined aborted:', combined.aborted);
server.close();
}
main();
The combined signal aborts through the timeout, so the user signal itself stays unaborted. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
fetch timeout -> TimeoutError
manual abort -> Error: user pressed cancel
sleep aborted -> AbortError
slowJob stopped by -> TimeoutError
slowJob without a signal: job finished
user signal aborted: false | combined aborted: true
Key points
abort() fires the abort event once and sets signal.reason.
AbortSignal.timeout and AbortSignal.any cover timeouts and combined cancellation.
Aborted calls reject with AbortError or TimeoutError.
Custom functions should accept a signal and clean up listeners.
Common mistakes
Reusing an aborted controller for a second request.
Forgetting to remove abort listeners, which leaks memory in long-lived signals.
Aborting but not stopping the real work behind the promise.
Treating AbortError and TimeoutError as the same thing in error handling.
Follow-ups
How do you cancel a stream pipeline?
How does a server learn that the client closed the connection?
What is the difference between signal.reason and the error you catch?
Tips
Say that promises cannot be cancelled, so the signal is a cooperative request.
Use AbortSignal.timeout for any outgoing HTTP call.
Mention cleanup of listeners to show care.
53.nodejs-0053Easyfresher
What are async iterators and async generators, and how do you use them with for await...of?
An async iterable has a [Symbol.asyncIterator]() method that returns an object whose next() returns a promise of { value, done }. An async generator function (async function*) creates one easily. for await...of reads values one at a time, waiting for each, and calls return() on the iterator when you break out early.
Full answer
A normal iterator hands out values one by one, but each value must be ready now. An async iterator hands out promises, so each value can arrive later: a page of an API, a chunk of a file, a message from a queue.
Async iterator: an object with next() that returns a promise of { value, done }.
Async generator: async function* name() { yield value; }. Node builds the iterator for you. You can await inside it, and yield values.
for await (const item of source) runs the loop body for each item, in order, waiting between items.
Why it is useful:
Pagination without loading all pages: yield items page by page, and stop fetching when the loop stops.
Streams are async iterable: for await (const chunk of readable) handles backpressure for you.
Early exit: break, return or throw inside the loop calls the iterator's return() method. In an async generator, that triggers finally blocks, so cleanup (closing a cursor or connection) runs.
Pipeline stages: async generator functions can be used in stream.pipeline and as transformations.
Notes: items are processed one after another, so a for await loop is sequential. For parallel work, collect promises or use a concurrency limit. Errors thrown by the source reject the loop, so wrap the loop in try/catch.
javascript
// A fake paginated API: 3 pages with 2 students each.
const pages = [['Asha', 'Ravi'], ['Meera', 'Kabir'], ['Zoya', 'Dev']];
const fetchPage = async (n) => {
await new Promise((r) => setTimeout(r, 5));
return { items: pages[n] || [], hasMore: n < pages.length - 1 };
};
// An async generator hides pagination from the caller.
async function* allStudents() {
let page = 0;
try {
while (true) {
const { items, hasMore } = await fetchPage(page++);
yield* items; // yields one student at a time
if (!hasMore) return;
}
} finally {
console.log('cleanup: the generator was closed after page', page);
}
}
// A hand-written async iterable.
const countdown = {
from: 3,
[Symbol.asyncIterator]() {
let n = this.from;
return {
async next() {
await new Promise((r) => setTimeout(r, 1));
return n > 0 ? { value: n--, done: false } : { value: undefined, done: true };
},
};
},
};
async function main() {
const all = [];
for await (const name of allStudents()) all.push(name);
console.log('all students:', all.join(', '));
// Stop early: the finally block still runs.
for await (const name of allStudents()) {
console.log('first student only:', name);
break;
}
const numbers = [];
for await (const n of countdown) numbers.push(n);
console.log('countdown:', numbers.join(' '));
}
main();
After break, the generator's finally block prints the page counter, which shows that early exit triggers cleanup. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
cleanup: the generator was closed after page 3
all students: Asha, Ravi, Meera, Kabir, Zoya, Dev
first student only: Asha
cleanup: the generator was closed after page 1
countdown: 3 2 1
Key points
Async iterables yield promises of values over time.
async function* is the easy way to write one.
for await is sequential and applies backpressure.
break calls return(), which runs finally blocks.
Common mistakes
Using for await on something that is not async iterable and not an array of promises.
Expecting for await to run items in parallel.
Forgetting try/finally for resources inside generators.
Mixing await in for...of on an array of promises, which does not wait for them in order of completion.
Follow-ups
How do you turn an event emitter into an async iterator?
What does yield* do in an async generator?
How would you process the pages in parallel while keeping the order?
Tips
Contrast with a callback: the consumer pulls the data.
Show the finally block on early exit.
Mention that readable streams are async iterable.
54.nodejs-0054Easyfresher
What does the node:timers/promises module offer, and how do you build a delay, a timeout and a polling loop with it?
timers/promises exports setTimeout, setImmediate and setInterval as promise-based functions, plus scheduler.wait and scheduler.yield. setTimeout resolves with a value after a delay, setInterval is an async iterator, and every function accepts an AbortSignal for cancellation.
Full answer
Instead of wrapping setTimeout in new Promise yourself, import the ready-made versions:
await sleep(ms, value): resolves with value after ms. A delay in an async function is one line.
await yieldNow(): resolves in the next check phase, which lets pending I/O run. scheduler.yield() does the same job for splitting long work.
scheduler.wait(ms, { signal }): like sleep, with an options object.
for await (const tick of every(ms, value)): an async iterator that produces a value every ms. Use break to stop it, or pass a signal.
Options for all of them: { signal } to cancel (the promise rejects with AbortError), and { ref: false } to avoid keeping the process alive.
Common recipes:
Timeout for any promise: Promise.race([work, sleep(ms).then(() => { throw new Error('timeout'); })]). Clear it with an AbortController, or the losing timer keeps running.
Polling until a condition is true, with a pause between checks, using the setInterval iterator.
Rate limiting in a loop: await sleep(100) between calls.
Important: setInterval from the promises module does not pile up calls when the loop body is slow. Ticks that happen while the body is running are not queued up forever, so slow work cannot create an endless backlog.
javascript
const { setTimeout: sleep, setInterval: every, setImmediate: yieldNow } = require('node:timers/promises');
async function waitUntil(check, { intervalMs = 10, timeoutMs = 200 } = {}) {
const controller = new AbortController();
const timeout = sleep(timeoutMs, undefined, { signal: controller.signal }).then(() => {
throw new Error('timed out waiting for the condition');
});
const polling = (async () => {
for await (const _ of every(intervalMs, undefined, { signal: controller.signal })) {
if (await check()) return 'condition became true';
}
})();
try {
return await Promise.race([timeout, polling]);
} finally {
controller.abort(); // stop the losing timer and the interval
}
}
async function main() {
console.log('value from sleep:', await sleep(5, 'rested'));
let attempts = 0;
const result = await waitUntil(() => ++attempts >= 3);
console.log(result, 'after', attempts, 'checks');
await waitUntil(() => false, { intervalMs: 10, timeoutMs: 50 }).catch((err) => console.log('second wait:', err.message));
let ticks = 0;
for await (const _ of every(5)) {
if (++ticks === 3) break;
}
console.log('interval ticks before break:', ticks);
const order = [];
setImmediate(() => order.push('immediate callback'));
Promise.resolve().then(() => order.push('promise callback'));
await yieldNow(); // resolves in the check phase, after the callbacks above
order.push('after yieldNow');
console.log('order:', order.join(' -> '));
}
main().catch((err) => console.log('unexpected:', err.message));
The helper cancels both the timer and the interval in finally, so nothing keeps the process alive after the function returns. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
value from sleep: rested
condition became true after 3 checks
second wait: timed out waiting for the condition
interval ticks before break: 3
order: promise callback -> immediate callback -> after yieldNow
Key points
sleep is one line: await setTimeout(ms).
setInterval from timers/promises is an async iterator.
Pass a signal to cancel, ref: false to not hold the process.
Cancel the timer in a timeout race, or it keeps running.
Common mistakes
Racing a timeout promise and never cancelling its timer.
Using sleep inside a loop for rate limiting without a signal.
Assuming the promise version of setImmediate runs before callbacks that were queued earlier.
Forgetting that the interval iterator ends only with break, return or a signal.
Follow-ups
How is scheduler.yield different from setImmediate?
How do you avoid keeping the process alive with a timer?
How would you add jitter to a polling loop?
Tips
Show the abort in finally, since that is the part people forget.
Mention timers/promises replaces the old new Promise(r => setTimeout(r, ms)) pattern.
Say ref: false for background timers.
55.nodejs-0055Hardsenior
How do you implement retries with exponential backoff and jitter for a flaky call?
Retry only temporary failures, wait longer after each attempt (base delay times factor to the attempt number, capped at a maximum), add random jitter so many clients do not retry together, limit the number of attempts, and stop when an AbortSignal fires. Make operations idempotent before retrying them.
Full answer
Networks and services fail briefly: a connection reset, a 503, a rate limit. A short pause and another try often works. A bad retry loop, however, can turn a small outage into a big one.
Design rules:
Retry only errors that can heal: network errors, timeouts, 429, 502, 503, 504. Never retry 400, 401, 403 or 404.
Exponential backoff: wait base * factor^attempt, for example 100 ms, 200 ms, 400 ms, 800 ms. This gives the other side time to recover.
Maximum delay and maximum attempts. Without them a loop can last for hours.
Jitter: add randomness. If 1,000 clients fail together and all wait exactly 200 ms, they all return together and fail again (a thundering herd). "Full jitter" picks a random delay between 0 and the backoff value. It spreads the load best.
Respect Retry-After headers when the server sends one.
Idempotency: a retry may repeat a request that already succeeded on the server. POST requests that create things need an idempotency key, or must not be retried.
Cancellation: pass an AbortSignal so shutdown or a user cancel stops the waiting.
A total deadline matters as much as an attempt count. Also consider a circuit breaker, which stops calling a service that keeps failing.
For tests, inject the sleep function and the random function. Then the code runs without real waiting and gives the same delays every time.
javascript
async function retry(task, options = {}) {
const {
retries = 3,
baseMs = 100,
factor = 2,
maxMs = 2000,
jitter = 'full', // 'none' or 'full'
isRetryable = () => true,
random = Math.random, // injected for tests
sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
signal,
} = options;
for (let attempt = 0; ; attempt++) {
signal?.throwIfAborted();
try {
return await task(attempt);
} catch (err) {
if (attempt >= retries || !isRetryable(err)) throw err;
const backoff = Math.min(maxMs, baseMs * factor ** attempt);
const delay = jitter === 'full' ? Math.floor(random() * backoff) : backoff;
await sleep(delay);
}
}
}
// A seeded random generator so the output is the same on every run.
function seeded(seed) {
return () => {
seed = (seed * 1664525 + 1013904223) % 4294967296;
return seed / 4294967296;
};
}
async function main() {
// The task fails twice with a temporary error, then works.
const makeTask = () => async (attempt) => {
if (attempt < 2) throw Object.assign(new Error('503 service busy'), { retryable: true });
return 'ok on attempt ' + (attempt + 1);
};
const delays = [];
const fakeSleep = async (ms) => { delays.push(ms); };
console.log(await retry(makeTask(), { jitter: 'none', sleep: fakeSleep }));
console.log('delays without jitter:', delays.join(', '));
delays.length = 0;
await retry(makeTask(), { jitter: 'full', sleep: fakeSleep, random: seeded(42) });
console.log('delays with full jitter (below the caps 100 and 200):', delays.join(', '));
// A permanent error is not retried.
const calls = [];
await retry(async () => { calls.push(1); throw Object.assign(new Error('404 not found'), { retryable: false }); },
{ sleep: fakeSleep, isRetryable: (e) => e.retryable })
.catch((err) => console.log('gave up at once:', err.message, '| calls:', calls.length));
// Too many failures: the last error is thrown after retries + 1 calls.
let count = 0;
await retry(async () => { count++; throw new Error('still down'); }, { retries: 2, sleep: fakeSleep })
.catch((err) => console.log('exhausted:', err.message, '| calls:', count));
}
main();
The sleep and random functions are injected, so the example prints the exact delays without waiting. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
ok on attempt 3
delays without jitter: 100, 200
delays with full jitter (below the caps 100 and 200): 25, 17
gave up at once: 404 not found | calls: 1
exhausted: still down | calls: 3
Key points
Retry only temporary errors.
Exponential backoff with a cap, a maximum attempt count and a total deadline.
Jitter prevents synchronized retries.
Idempotency decides whether a retry is safe.
Inject sleep and random to make tests fast and stable.
Common mistakes
Retrying every error, including validation failures.
Retrying without jitter and without a limit.
Retrying non-idempotent writes and creating duplicates.
Hiding the final error after the last attempt.
Follow-ups
What is a circuit breaker and how does it differ from a retry?
How would you honour a Retry-After header?
How do idempotency keys work?
Tips
Name the thundering herd problem when you explain jitter.
State the retryable list (429, 502, 503, 504, network errors).
Say that injected sleep and random keep tests fast and exact.
56.nodejs-0056Hardsenior
Can race conditions happen in single-threaded Node.js, and how do you serialize async work with a mutex or queue?
Yes. Between an await and the code after it, other callbacks can run, so a read-modify-write across an await can lose updates. Serialize such sections with a promise-based mutex or a queue, or move the whole update into one atomic operation such as a database transaction or an atomic SQL update.
Full answer
JavaScript runs one piece of code at a time, so a counter++ in plain code is safe. The danger starts when an await sits inside the update:
Task A reads balance = 100.
await something (a database call, a delay).
Meanwhile task B reads balance = 100 too.
A writes 150. B writes 150. One deposit is lost.
The same problem appears with cached files that are read, changed and written back, with "check then create" logic, and with counters in memory shared between concurrent requests.
Solutions, from best to simplest:
Make the operation atomic where the data lives: UPDATE accounts SET balance = balance + 50, a Redis INCR, or a database transaction with the right isolation level or row lock.
Serialize in the process with a mutex. A promise-based mutex keeps a chain: each caller waits for the previous holder to finish, then runs. Always release in finally.
Use a queue with concurrency 1 per key (for example one queue per account id) to keep unrelated work parallel.
Avoid shared mutable state. Have one owner function or worker and send messages.
A process mutex protects only one process. With several servers or cluster workers, you need a distributed lock or database-level atomic operations. Also keep critical sections short, since waiting tasks form a line and a slow holder blocks everyone.
javascript
class Mutex {
#tail = Promise.resolve();
async run(task) {
let release;
const gate = new Promise((resolve) => { release = resolve; });
const previous = this.#tail;
this.#tail = previous.then(() => gate); // the next caller waits for this gate
await previous; // wait for the earlier holder
try {
return await task();
} finally {
release(); // always let the next caller in
}
}
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function deposit(account, amount) {
const current = account.balance; // read
await wait(5); // a database call, for example
account.balance = current + amount; // write: may overwrite someone else's update
}
async function main() {
// Without a lock: three deposits of 50 run at the same time.
const unsafe = { balance: 100 };
await Promise.all([deposit(unsafe, 50), deposit(unsafe, 50), deposit(unsafe, 50)]);
console.log('without lock, expected 250, got:', unsafe.balance);
// With a mutex: the deposits run one after another.
const safe = { balance: 100 };
const mutex = new Mutex();
await Promise.all([1, 2, 3].map(() => mutex.run(() => deposit(safe, 50))));
console.log('with mutex, expected 250, got: ', safe.balance);
// An error inside the lock does not block later callers.
const failing = mutex.run(async () => { throw new Error('task failed'); });
await failing.catch((err) => console.log('first task:', err.message));
console.log('later task still runs:', await mutex.run(async () => 'ran after the failure'));
}
main();
The unsafe version loses two of the three deposits because every call read the same starting balance. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
without lock, expected 250, got: 150
with mutex, expected 250, got: 250
first task: task failed
later task still runs: ran after the failure
Key points
An await inside read-modify-write allows interleaving.
Atomic operations in the datastore are the best fix.
A mutex is a promise chain. Always release in finally.
Per-key queues keep unrelated work parallel.
A process mutex does not protect several processes.
Common mistakes
Believing single-threaded means no race conditions.
Forgetting to release the lock when the task throws.
Using an in-memory mutex when the app runs on several servers.
Holding a lock during a slow network call.
Follow-ups
How would you lock per account id instead of globally?
How does a database row lock differ from a process mutex?
How do optimistic locks with version numbers work?
Tips
Walk through the four-step interleaving.
Say 'make it atomic in the database' before you offer a mutex.
Mention the multi-process limitation.
57.nodejs-0057Easyfresher
How do you write and run tests with the built-in node:test module?
node:test is a test runner built into Node. Write tests with test() or describe() and it(), check results with node:assert, and run them with node --test. It supports hooks, skipping, subtests, mocking, coverage and several reporters, so small projects need no extra dependency.
Full answer
Since Node 20 the built-in runner is stable. A test file looks like this:
Run node --test. It finds files named *.test.js, *.spec.js, files in a test folder, and runs each file in its own process, in parallel.
Features:
describe and it (also suite): grouping, same idea as Jest and Mocha.
Hooks: before, after, beforeEach, afterEach.
test options: { skip: true }, { todo: true }, { only: true } with --test-only, { timeout: 1000 }, { concurrency: n }.
Async tests: return a promise or use an async function. A rejected promise fails the test.
Subtests: t.test(...) inside a test, and the context t gives t.mock, t.skip and t.diagnostic.
Reporters: spec (the default in a terminal), tap, dot, junit, lcov. Choose with --test-reporter.
Coverage: node --test --experimental-test-coverage (check the current flag name in the docs for your version).
Watch mode: node --test --watch.
Name filters: --test-name-pattern.
Exit code: 0 if all tests pass, 1 if any fail, which is what CI needs.
When to pick something else: if you need snapshot testing, a large plugin ecosystem or DOM tests, Jest or Vitest may fit better. For a backend library or service, node:test is often enough.
The run uses the tap reporter so that the output is easy to read in a script. One test fails on purpose, to show the exit code. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
ok 1 - gives A for 75 and above
ok 2 - gives B for passing marks
ok 3 - gives F below 40
ok 4 - is skipped on purpose (skipped)
ok 1 - grade()
not ok 2 - this test fails (error on purpose)
tests 5
pass 3
fail 1
skipped 1
exit code: 1
Key points
node --test finds and runs test files.
test, describe, it and hooks work like other runners.
Pair it with node:assert.
Exit code 1 on failure, so CI works with no setup.
Common mistakes
Forgetting to name files so the runner finds them.
Using the old assert module (loose equality) instead of node:assert/strict.
Sharing state between tests without resetting it in beforeEach.
Not awaiting async work, so a test passes before the work ends.
Follow-ups
How does node:test run files in parallel and does it affect shared databases?
How do you run a single test by name?
How do you produce a JUnit report for CI?
Tips
Mention that it is built in and stable, which removes dependencies.
Use assert/strict by default.
Show that the exit code is how CI knows a test failed.
58.nodejs-0058Easyfresher
What is the difference between assert.equal and assert.strictEqual, and between deepEqual and deepStrictEqual?
assert.equal and deepEqual use loose comparison (==), so 1 equals '1'. strictEqual and deepStrictEqual use Object.is style comparison and also compare prototypes for objects. Use node:assert/strict so that the short names are strict. assert.throws and assert.rejects check errors from sync and async code.
Full answer
The assert module throws an AssertionError when a check fails, and a test runner turns that into a failed test.
Legacy mode (require('node:assert')):
assert.equal(a, b) uses ==. So 1 equals '1', and null equals undefined.
assert.deepEqual compares objects with loose rules.
Strict mode (require('node:assert/strict'), or assert.strict):
equal means strictEqual (uses Object.is, so NaN equals NaN and +0 does not equal -0).
deepEqual means deepStrictEqual: same keys, same values with strict comparison, and same prototype. {a: 1} and an instance of a class with a: 1 are different.
Failure messages show a readable diff.
Useful helpers:
assert.ok(value) or assert(value): truthy check.
assert.throws(fn, expected): the function must throw. expected can be an error class, a regular expression for the message, an object with properties (code, message), or a validation function.
assert.rejects(promiseOrFn, expected): the async version. Always await it, or the test ends before the check runs.
assert.doesNotReject, assert.match(string, regexp), assert.notStrictEqual, assert.deepStrictEqual with Maps and Sets.
AssertionError has actual, expected, operator and code ('ERR_ASSERTION').
Use strict mode in all new tests. Loose comparison hides bugs, for example a function that returns the string '3' instead of the number 3.
javascript
const loose = require('node:assert');
const strict = require('node:assert/strict');
function attempt(label, fn) {
try {
fn();
console.log(label.padEnd(44), 'passes');
} catch (err) {
console.log(label.padEnd(44), 'fails with', err.code, '/ operator', err.operator);
}
}
attempt("loose equal(1, '1')", () => loose.equal(1, '1'));
attempt("strictEqual(1, '1')", () => loose.strictEqual(1, '1'));
attempt('loose deepEqual({a: 1}, {a: "1"})', () => loose.deepEqual({ a: 1 }, { a: '1' }));
attempt('deepStrictEqual({a: 1}, {a: "1"})', () => strict.deepEqual({ a: 1 }, { a: '1' }));
class Point { constructor() { this.x = 1; } }
attempt('deepEqual(new Point(), {x: 1}) loose', () => loose.deepEqual(new Point(), { x: 1 }));
attempt('deepEqual(new Point(), {x: 1}) strict', () => strict.deepEqual(new Point(), { x: 1 }));
attempt('strictEqual(NaN, NaN)', () => strict.equal(NaN, NaN));
// Checking errors
strict.throws(() => JSON.parse('{bad'), { name: 'SyntaxError' });
console.log('assert.throws matched a SyntaxError');
async function main() {
await strict.rejects(Promise.reject(new RangeError('marks out of range')), { name: 'RangeError', message: /out of range/ });
console.log('assert.rejects matched the RangeError');
// Forgetting to await would let the test end before this check runs.
await strict.rejects(async () => { throw new TypeError('x'); }, TypeError);
console.log('assert.rejects accepts an async function too');
}
main();
The first four rows show how loose and strict comparison differ for the same values. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
loose equal(1, '1') passes
strictEqual(1, '1') fails with ERR_ASSERTION / operator strictEqual
loose deepEqual({a: 1}, {a: "1"}) passes
deepStrictEqual({a: 1}, {a: "1"}) fails with ERR_ASSERTION / operator deepStrictEqual
deepEqual(new Point(), {x: 1}) loose passes
deepEqual(new Point(), {x: 1}) strict fails with ERR_ASSERTION / operator deepStrictEqual
strictEqual(NaN, NaN) passes
assert.throws matched a SyntaxError
assert.rejects matched the RangeError
assert.rejects accepts an async function too
Key points
Import node:assert/strict so short names are strict.
deepStrictEqual compares prototypes and uses strict value checks.
assert.throws and assert.rejects check errors. Await rejects.
AssertionError exposes actual, expected and operator.
Common mistakes
Using assert.equal and getting a pass for 1 and '1'.
Forgetting await before assert.rejects.
Comparing class instances with plain objects and expecting a pass in strict mode.
Using assert.throws on an async function, which returns a promise and does not throw.
Follow-ups
How does deepStrictEqual compare Maps, Sets and Dates?
What does Object.is do differently from ===?
How do you assert an error code and message together?
Tips
Say 'import assert/strict' as the habit.
Show NaN and prototype cases to prove depth.
Warn about the missing await on rejects.
59.nodejs-0059Mediummid
How do you create mocks, spies and fake timers with node:test?
mock.fn() creates a function that records calls and can have an implementation. mock.method(object, 'name') replaces a method and can restore it. mock.timers.enable() replaces setTimeout and setInterval so that tests move time with tick() and never wait. Mocks created in a test context are restored automatically.
Full answer
A test double stands in for a real dependency (the email service, the clock, the database) so a test is fast and predictable.
In node:test, the mock object gives you:
mock.fn(implementation?): a spy function. fn.mock.calls is an array of call records with arguments, result, error and this. fn.mock.callCount() returns the number of calls. fn.mock.mockImplementation(newFn) and mockImplementationOnce change behaviour.
mock.method(object, 'method', implementation?): replaces a method with a mock. The original is restored by mock.restoreAll() or by the test context (t.mock.method) when the test ends. Use { getter: true } or { setter: true } for accessors.
mock.timers.enable({ apis: ['setTimeout', 'setInterval', 'Date'] }): fake time. mock.timers.tick(ms) moves the fake clock forward and runs due timers. Always call mock.timers.reset() (or use t.mock.timers) so later tests get real timers.
mock.module and mock.getter are available in newer versions for module-level mocks (check your version).
Guidelines:
Prefer passing dependencies as arguments (dependency injection). Then a test passes a mock.fn() and needs no patching.
Check behaviour that matters (the email was sent once to the right address), not private details.
Do not mock everything. A test full of mocks proves only that the mocks work.
Use the context version (t.mock) inside tests so clean-up is automatic.
javascript
const { mock } = require('node:test');
const assert = require('node:assert/strict');
// Code under test: notify a student, and retry the send after 1 hour if it fails.
function createNotifier({ sendEmail, setTimeoutFn = setTimeout }) {
return async function notify(student, message) {
try {
await sendEmail(student.email, message);
return 'sent';
} catch {
setTimeoutFn(() => notify(student, message), 60 * 60 * 1000);
return 'retry scheduled';
}
};
}
async function main() {
// 1. A spy function with a changing behaviour.
const sendEmail = mock.fn(async () => { throw new Error('mail server down'); });
mock.timers.enable({ apis: ['setTimeout'] });
const notify = createNotifier({ sendEmail });
const student = { email: 'asha@example.com' };
console.log('first call:', await notify(student, 'Result published'));
console.log('send calls so far:', sendEmail.mock.callCount());
// 2. The server recovers. Move the fake clock one hour ahead.
sendEmail.mock.mockImplementation(async () => {});
mock.timers.tick(60 * 60 * 1000);
await new Promise((resolve) => setImmediate(resolve)); // let the retry promise settle
console.log('send calls after one fake hour:', sendEmail.mock.callCount());
console.log('arguments of the last call:', sendEmail.mock.calls.at(-1).arguments);
mock.timers.reset();
// 3. mock.method replaces a method and restores it.
const calendar = { today: () => '2026-12-04' };
mock.method(calendar, 'today', () => '2027-01-01');
console.log('mocked method:', calendar.today());
mock.restoreAll();
console.log('restored method:', calendar.today());
assert.equal(sendEmail.mock.callCount(), 2);
}
main();
No real hour passes. The fake clock moves forward and runs the retry timer at once. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
first call: retry scheduled
send calls so far: 1
send calls after one fake hour: 2
arguments of the last call: [ 'asha@example.com', 'Result published' ]
mocked method: 2027-01-01
restored method: 2026-12-04
Key points
mock.fn is a spy with call records.
mock.method replaces and restores methods.
mock.timers.tick moves fake time without waiting.
Use t.mock inside tests for automatic restore.
Prefer dependency injection to patching.
Common mistakes
Forgetting mock.timers.reset() and breaking later tests.
Mocking the function under test instead of its dependency.
Asserting on the number of calls only and not on the arguments.
Patching global objects without restoring them.
Follow-ups
How does t.mock differ from the global mock?
How would you mock fetch in tests?
What is the difference between a mock, a stub and a spy?
Tips
Define the three words stub, spy, mock in one line each.
Say you prefer injection to patching.
Show fake timers as the answer to slow tests.
60.nodejs-0060Mediummid
How do you test an HTTP server in Node.js without hard-coding a port?
Export a function that builds the server without calling listen, start it in the test with listen(0) so the system picks a free port, call it with fetch, and close it in an after hook. Tests then run in parallel without port clashes, and the same code works in the real app.
Full answer
Hard-coded ports (3000) make tests fail when two test files run at once, or when a developer's app is already running. The clean approach:
Split the application from the start-up. app.js exports createServer(dependencies) and returns an http.Server (or an Express or Fastify instance). server.js calls listen(process.env.PORT). Tests import app.js only.
In a test, call server.listen(0, '127.0.0.1'). Port 0 means "any free port". Read it from server.address().port.
Call the server with fetch (built in), and check status, headers and JSON body.
Close the server in an after hook (server.close(), and server.closeAllConnections() to avoid waiting for keep-alive connections).
Inject dependencies: pass a fake database or clock into createServer so the test controls data.
What to test:
Status codes for success, validation errors and not found.
Response shape and headers (content type, cache headers).
Error paths: invalid JSON, large body, a failing dependency answers 500 without leaking details.
Behaviour, not framework internals.
Frameworks help: Fastify has app.inject() that simulates a request without opening a port, and supertest does something similar for Express. Both are good for speed, but one test with a real socket is still worth having.
javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'http-test-'));
fs.writeFileSync(path.join(dir, 'app.js'), `
const http = require('node:http');
// The app is built from its dependencies. Nothing here calls listen().
exports.createServer = ({ students }) => http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
const match = url.pathname.match(/^\\/students\\/(\\d+)$/);
res.setHeader('Content-Type', 'application/json');
if (req.method === 'GET' && match) {
const student = students.find((s) => s.id === Number(match[1]));
res.statusCode = student ? 200 : 404;
return res.end(JSON.stringify(student || { error: 'not found' }));
}
res.statusCode = 405;
res.end(JSON.stringify({ error: 'method not allowed' }));
});
`);
fs.writeFileSync(path.join(dir, 'app.test.js'), `
const { describe, it, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { createServer } = require('./app.js');
describe('students API', () => {
let server, base;
before(async () => {
server = createServer({ students: [{ id: 1, name: 'Asha' }] });
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = 'http://127.0.0.1:' + server.address().port;
});
after(() => { server.closeAllConnections(); server.close(); });
it('returns a known student', async () => {
const res = await fetch(base + '/students/1');
assert.equal(res.status, 200);
assert.match(res.headers.get('content-type'), /application\\/json/);
assert.deepEqual(await res.json(), { id: 1, name: 'Asha' });
});
it('returns 404 for an unknown student', async () => {
const res = await fetch(base + '/students/99');
assert.equal(res.status, 404);
});
it('rejects other methods with 405', async () => {
const res = await fetch(base + '/students/1', { method: 'DELETE' });
assert.equal(res.status, 405);
});
});
`);
const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap'], { encoding: 'utf8', cwd: dir });
const lines = run.stdout.split('\n');
console.log(lines.filter((l) => /^\s*(ok|not ok) \d+ - /.test(l)).join('\n'));
console.log('pass:', lines.find((l) => l.startsWith('# pass ')).split(' ')[2], '| fail:', lines.find((l) => l.startsWith('# fail ')).split(' ')[2]);
fs.rmSync(dir, { recursive: true });
The app file and the test file are written into a temporary folder, and the test runner is started on it, so the snippet shows the whole setup. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
ok 1 - returns a known student
ok 2 - returns 404 for an unknown student
ok 3 - rejects other methods with 405
ok 1 - students API
pass: 3 | fail: 0
Key points
Do not call listen in the module that tests import.
Use port 0 and read server.address().port.
Close the server in an after hook.
Inject dependencies so tests control data.
Common mistakes
Calling listen(3000) inside the module and getting EADDRINUSE in parallel tests.
Leaving the server open, so the test process never exits.
Testing with real production data.
Only testing the happy path.
Follow-ups
How does Fastify inject differ from a real socket test?