Questions 81–100 of 200 · 0 of 20 on this page marked learned
81.nodejs-0081Mediummid
How do you encrypt and decrypt data with AES-256-GCM in Node.js, and what are the rules for the key, the IV and the auth tag?
AES-256-GCM encrypts data and also authenticates it. You need a 32-byte key, a unique 12-byte IV (nonce) for every message, and you must store the 16-byte auth tag next to the ciphertext. On decryption, final() throws if the data or tag was changed. Never reuse an IV with the same key.
Full answer
Symmetric encryption uses one secret key for both encrypting and decrypting. GCM mode is an authenticated mode: besides hiding the content, it produces an authentication tag that proves nothing was altered. Older modes such as CBC without a MAC allow silent tampering.
Ingredients:
Key: 32 random bytes for AES-256. Get it from a secret manager, or derive it from a password with scrypt and a salt. Do not use a plain password as a key.
IV (nonce): 12 random bytes, new for every message. With GCM, reusing an IV under the same key breaks the security badly. Store the IV with the ciphertext (it is not secret).
Auth tag: 16 bytes, from cipher.getAuthTag() after final(). Store it too, and give it back with decipher.setAuthTag() before final().
Additional authenticated data (AAD): optional plain data (a record id, a version) that is not encrypted but is covered by the tag. It binds the ciphertext to its context.
tag = cipher.getAuthTag(). Save iv, ciphertext and tag together (for example iv | tag | ciphertext).
To decrypt, create a decipher with the same key and iv, call setAuthTag(tag), then update and final. If anything was altered, final() throws an error and you must not use the output.
Notes: never log keys or plaintext, plan key rotation (store a key id with the data), and remember that encryption does not hide the data size. For passwords use hashing, not encryption.
javascript
const crypto = require('node:crypto');
function encrypt(plaintext, key, aad) {
const iv = crypto.randomBytes(12); // new for every message
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
if (aad) cipher.setAAD(Buffer.from(aad));
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag(); // 16 bytes
return Buffer.concat([iv, tag, ciphertext]); // layout: iv | tag | ciphertext
}
function decrypt(packed, key, aad) {
const iv = packed.subarray(0, 12);
const tag = packed.subarray(12, 28);
const ciphertext = packed.subarray(28);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
if (aad) decipher.setAAD(Buffer.from(aad));
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'); // final() throws on tampering
}
const key = crypto.randomBytes(32);
const message = 'Asha scored 78 in Maths';
const packed = encrypt(message, key, 'student:42');
console.log('packed length = 12 (iv) + 16 (tag) + message bytes:', packed.length === 12 + 16 + Buffer.byteLength(message));
console.log('round trip works:', decrypt(packed, key, 'student:42') === message);
const second = encrypt(message, key, 'student:42');
console.log('same message, different output (random IV):', !packed.equals(second));
function tryDecrypt(label, data, k, aad) {
try {
decrypt(data, k, aad);
console.log(label, '-> accepted');
} catch (err) {
console.log(label, '-> rejected:', err.message);
}
}
const tampered = Buffer.from(packed);
tampered[tampered.length - 1] ^= 1; // flip one bit of the ciphertext
tryDecrypt('tampered ciphertext', tampered, key, 'student:42');
tryDecrypt('wrong context (aad)', packed, key, 'student:43');
tryDecrypt('wrong key', packed, crypto.randomBytes(32), 'student:42');
Three decryption attempts fail on purpose (error on purpose): a changed bit, the wrong context and the wrong key. All three throw the same authentication error. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
packed length = 12 (iv) + 16 (tag) + message bytes: true
round trip works: true
same message, different output (random IV): true
tampered ciphertext -> rejected: Unsupported state or unable to authenticate data
wrong context (aad) -> rejected: Unsupported state or unable to authenticate data
wrong key -> rejected: Unsupported state or unable to authenticate data
Key points
Key: 32 random bytes. IV: 12 bytes, unique per message.
Store IV and auth tag with the ciphertext.
final() throws when data or tag was tampered with.
AAD binds the ciphertext to its context.
Never reuse an IV with the same key.
Common mistakes
Reusing an IV or using a counter that restarts after a crash.
Forgetting to store the auth tag.
Using the decrypted output before final() has succeeded.
Using a human password directly as the key.
Follow-ups
Why is GCM better than CBC for most uses?
How would you rotate encryption keys for stored data?
What is envelope encryption?
Tips
Name the three stored items: IV, tag, ciphertext.
Say 'authenticated encryption' and explain tampering.
State the IV rule firmly.
82.nodejs-0082Hardsenior
How do digital signatures (Ed25519) and key agreement (X25519) work in Node.js crypto, and when would you use each?
A digital signature proves who created a message and that it was not changed: the private key signs, anyone with the public key verifies. Key agreement (ECDH with X25519) lets two parties each combine their own private key with the other's public key and get the same shared secret, which a KDF such as HKDF turns into encryption keys.
Full answer
Asymmetric cryptography uses a key pair: a private key (secret) and a public key (shareable).
Signatures:
Purpose: authenticity and integrity. Examples: signed software updates, JWTs with RS256 or EdDSA, signed API requests, license files.
Ed25519 is a modern, fast signature scheme with small keys (32 bytes) and no parameter choices to get wrong.
Node: crypto.generateKeyPairSync('ed25519'), crypto.sign(null, data, privateKey), crypto.verify(null, data, publicKey, signature). The algorithm argument is null for Ed25519, because the hash is part of the scheme.
A signature does not hide the data. It only proves origin and integrity.
Key agreement:
Purpose: two parties who have never shared a secret create one over an open channel. This is the core of TLS.
X25519: each side generates a key pair, sends its public key, and computes crypto.diffieHellman({ privateKey, publicKey: otherPublic }). Both get the same bytes.
Never use the raw shared secret as a key. Pass it through a KDF: crypto.hkdfSync('sha256', secret, salt, info, 32), which gives well-distributed key material bound to a context string (info).
Plain key agreement does not authenticate the other side. An attacker in the middle can substitute public keys, so real protocols add signatures or certificates.
Choosing: signatures when someone must prove who made something. Key agreement when two parties need a fresh shared key for symmetric encryption. In practice, use TLS or a vetted protocol rather than building your own.
Key storage: export keys as PEM or JWK (keyObject.export), keep private keys in a secret manager or hardware module, and rotate them with key ids.
javascript
const crypto = require('node:crypto');
// 1. Digital signature with Ed25519
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
const document = Buffer.from('Certificate: Asha completed Node.js, grade A');
const signature = crypto.sign(null, document, privateKey);
console.log('signature length:', signature.length, 'bytes');
console.log('valid signature verifies:', crypto.verify(null, document, publicKey, signature));
console.log('changed document fails: ', !crypto.verify(null, Buffer.from('Certificate: Asha completed Node.js, grade A+'), publicKey, signature));
console.log('another key fails: ', !crypto.verify(null, document, crypto.generateKeyPairSync('ed25519').publicKey, signature));
console.log('public key as PEM starts with:', publicKey.export({ type: 'spki', format: 'pem' }).split('\n')[0]);
// 2. Key agreement with X25519: Alice and Bob never send a secret.
const alice = crypto.generateKeyPairSync('x25519');
const bob = crypto.generateKeyPairSync('x25519');
const aliceSecret = crypto.diffieHellman({ privateKey: alice.privateKey, publicKey: bob.publicKey });
const bobSecret = crypto.diffieHellman({ privateKey: bob.privateKey, publicKey: alice.publicKey });
console.log('both sides computed the same secret:', aliceSecret.equals(bobSecret));
// 3. Turn the shared secret into a proper key with HKDF
const salt = crypto.randomBytes(16);
const keyForAlice = Buffer.from(crypto.hkdfSync('sha256', aliceSecret, salt, 'chat-messages-v1', 32));
const keyForBob = Buffer.from(crypto.hkdfSync('sha256', bobSecret, salt, 'chat-messages-v1', 32));
const otherPurpose = Buffer.from(crypto.hkdfSync('sha256', aliceSecret, salt, 'file-uploads-v1', 32));
console.log('derived keys match:', keyForAlice.equals(keyForBob));
console.log('a different context gives a different key:', !keyForAlice.equals(otherPurpose));
Key pairs are random, so the snippet prints facts that are always true instead of key bytes. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
signature length: 64 bytes
valid signature verifies: true
changed document fails: true
another key fails: true
public key as PEM starts with: -----BEGIN PUBLIC KEY-----
both sides computed the same secret: true
derived keys match: true
a different context gives a different key: true
Key points
Signatures: private key signs, public key verifies.
Ed25519 passes null as the algorithm to sign and verify.
X25519 gives both sides the same shared secret.
Run the shared secret through HKDF before using it.
Key agreement alone does not prove identity.
Common mistakes
Using the raw Diffie-Hellman output as an encryption key.
Assuming key agreement proves who the other side is.
Signing a hash that the verifier cannot reproduce.
Keeping the private key in the repository.
Follow-ups
How do JWT signature algorithms HS256 and EdDSA differ?
What is forward secrecy?
How do certificates solve the identity problem?
Tips
Start from what each tool proves or creates.
Say HKDF after the shared secret.
Note that you would use TLS in practice, not hand-built protocols.
83.nodejs-0083Easyfresher
How do the URL and URLSearchParams classes work, and how do they differ from the legacy url.parse and querystring modules?
URL is the standard (WHATWG) parser available in Node and browsers. It splits an address into protocol, host, pathname, search and hash, and URLSearchParams reads and builds the query string with correct encoding. The legacy url.parse() and the querystring module are older, behave differently on edge cases and should not be used in new code.
Full answer
new URL(input, base) parses an absolute address, or a relative one with a base. It throws a TypeError on invalid input, and URL.canParse(input) checks without throwing (Node 19.9 and later).
Properties: protocol ('https:'), username and password, hostname, port (a string, empty for the default), host (hostname plus port), pathname ('/a/b'), search ('?x=1'), hash ('#top'), origin, href. Properties can be set, and the URL updates and re-encodes itself.
URLSearchParams works on the query:
url.searchParams.get('x') returns the first value or null. getAll('x') returns all. has, set (replace), append (add another), delete, sort.
Iteration gives [key, value] pairs. new URLSearchParams({ a: 1 }) or from an array of pairs builds one. toString() gives an encoded string.
Values are decoded and encoded for you: a space becomes + in the query string form, special characters become %XX.
Why not string concatenation: 'https://x.com/?q=' + term breaks when term has &, = or #, and it can allow parameter injection. Use searchParams.set or append.
Legacy APIs:
url.parse() has inconsistent parsing and was involved in security issues, because different parsers read the same string in different ways. It is deprecated.
querystring.parse and stringify handle repeated keys and encoding slightly differently from URLSearchParams. Prefer URLSearchParams.
url.fileURLToPath and pathToFileURL convert between file URLs and paths, which matters in ES modules.
The URL parser also normalizes: lower-cases the host, removes the default port, resolves ../ segments and converts IP forms such as 0x7f.1 to 127.0.0.1.
javascript
const url = new URL('https://user:pass@Schoolabe.com:443/courses/node/../react?level=fresher&tag=a&tag=b#reviews');
console.log('protocol:', url.protocol, '| hostname:', url.hostname, '| port:', JSON.stringify(url.port));
console.log('pathname (resolved):', url.pathname, '| hash:', url.hash, '| origin:', url.origin);
console.log('get level:', url.searchParams.get('level'), '| getAll tag:', url.searchParams.getAll('tag'));
// Building a query safely: special characters are encoded for you.
const search = new URL('https://schoolabe.com/search');
search.searchParams.set('q', 'node & express #1');
search.searchParams.append('page', 2);
console.log('built:', search.href);
// set replaces, append adds, delete removes.
search.searchParams.set('page', 3);
search.searchParams.delete('q');
console.log('after set and delete:', search.search);
// Relative addresses need a base.
console.log('resolved:', new URL('../fees?plan=pro', 'https://schoolabe.com/courses/node/').href);
// Invalid input
console.log('canParse("not a url"):', URL.canParse('not a url'), '| canParse("http://x.org"):', URL.canParse('http://x.org'));
// The parser normalizes odd host spellings.
console.log('0x7f.1 becomes:', new URL('http://0x7f.1/').hostname);
// Iteration and conversion
const params = new URLSearchParams({ a: '1', b: 'two words' });
console.log('entries:', [...params], '| string:', params.toString());
console.log('to object (last value wins):', Object.fromEntries(new URLSearchParams('x=1&x=2&y=3')));
The parser removes the default port 443, resolves the .. segment and lower-cases the host. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
protocol: https: | hostname: schoolabe.com | port: ""
pathname (resolved): /courses/react | hash: #reviews | origin: https://schoolabe.com
get level: fresher | getAll tag: [ 'a', 'b' ]
built: https://schoolabe.com/search?q=node+%26+express+%231&page=2
after set and delete: ?page=3
resolved: https://schoolabe.com/courses/fees?plan=pro
canParse("not a url"): false | canParse("http://x.org"): true
0x7f.1 becomes: 127.0.0.1
entries: [ [ 'a', '1' ], [ 'b', 'two words' ] ] | string: a=1&b=two+words
to object (last value wins): { x: '2', y: '3' }
Key points
new URL(input, base) parses and normalizes.
searchParams handles encoding. Do not concatenate query strings.
URL.canParse checks without exceptions.
url.parse and querystring are legacy.
Common mistakes
Building query strings by joining text.
Forgetting that searchParams.get returns a string or null.
Calling new URL on user input without try/catch.
Using Object.fromEntries on repeated keys and losing values.
Follow-ups
Why is url.parse considered unsafe?
How does URLSearchParams encode a space?
How do you convert a file URL to a path?
Tips
Use the set versus append difference as a quick check.
Mention URL.canParse.
Say 'never concatenate query strings'.
84.nodejs-0084Hardsenior
How do you validate a user-supplied URL to prevent server-side request forgery (SSRF) in a Node.js service?
SSRF happens when a server fetches a URL chosen by a user, and the user points it at internal addresses such as 127.0.0.1 or cloud metadata at 169.254.169.254. Allow only http and https, parse with URL, resolve the host name yourself, reject private and special IP ranges (net.BlockList), connect to the checked IP, and limit redirects.
Full answer
Features such as "import from URL", webhooks, link previews and image fetchers make the server send requests for a user. An attacker supplies http://169.254.169.254/latest/meta-data/ (cloud credentials), http://localhost:6379 (a local Redis) or an internal admin address. The server may then return secrets or change internal systems.
A defence needs several layers, because simple string checks fail:
Parse with the URL class and allow only http: and https:. Reject file:, ftp:, gopher: and others. Reject credentials in the URL (user@host), which are used in confusion tricks.
Normalise the host. The URL parser converts 0x7f.1 or 2130706433 to 127.0.0.1, which is why you must check the parsed result, not the raw text.
Resolve the host name to IP addresses (dns.lookup with all: true). Reject every address that is loopback, private (10/8, 172.16/12, 192.168/16), link-local (169.254/16), carrier-grade NAT, multicast or IPv6 equivalents. net.BlockList helps with ranges. If any address is blocked, reject.
Connect to the IP you checked, not to the name again. Otherwise DNS rebinding changes the answer between the check and the connection. Pass a custom lookup function to the HTTP agent, or set the Host header and connect to the IP.
Do not follow redirects blindly. A public URL can redirect to an internal one. Follow manually, with a small limit, and run the full check on each hop.
Add timeouts, a response size limit and a restricted set of ports.
Network-level controls matter most: run fetchers in a network segment without access to internal services, and require metadata service tokens (IMDSv2 on AWS).
An allow-list of known hosts is stronger than a block-list whenever the use case permits it.
javascript
const net = require('node:net');
const blocked = new net.BlockList();
blocked.addSubnet('127.0.0.0', 8);
blocked.addSubnet('10.0.0.0', 8);
blocked.addSubnet('172.16.0.0', 12);
blocked.addSubnet('192.168.0.0', 16);
blocked.addSubnet('169.254.0.0', 16); // link-local, includes the cloud metadata address
blocked.addSubnet('0.0.0.0', 8);
blocked.addAddress('::1', 'ipv6');
blocked.addSubnet('fc00::', 7, 'ipv6'); // unique local addresses
blocked.addSubnet('fe80::', 10, 'ipv6');
// A pretend DNS: name -> addresses. A real service would call dns.promises.lookup(host, { all: true }).
const fakeDns = {
'schoolabe.com': ['93.184.216.34'],
'intranet.example': ['10.2.3.4'],
'sneaky.example': ['93.184.216.34', '127.0.0.1'], // one public and one private answer
};
const resolve = async (host) => fakeDns[host] || [];
async function checkUrl(input) {
let url;
try { url = new URL(input); } catch { return 'rejected: not a valid URL'; }
if (!['http:', 'https:'].includes(url.protocol)) return 'rejected: protocol ' + url.protocol;
if (url.username || url.password) return 'rejected: credentials in the URL';
const host = url.hostname.replace(/^\[|\]$/g, '');
const addresses = net.isIP(host) ? [host] : await resolve(host);
if (addresses.length === 0) return 'rejected: host does not resolve';
for (const address of addresses) {
const family = net.isIP(address) === 6 ? 'ipv6' : 'ipv4';
if (blocked.check(address, family)) return 'rejected: ' + address + ' is a private address';
}
return 'allowed (connect to ' + addresses[0] + ')';
}
(async () => {
const inputs = [
'https://schoolabe.com/image.png',
'http://127.0.0.1:6379/',
'http://0x7f.1/', // the parser turns this into 127.0.0.1
'http://2130706433/', // decimal form of 127.0.0.1
'http://169.254.169.254/latest/meta-data/',
'http://[::1]/admin',
'http://intranet.example/',
'http://sneaky.example/',
'http://schoolabe.com@127.0.0.1/', // the real host is after the @
'file:///etc/passwd',
'ftp://schoolabe.com/file',
'not a url',
];
for (const input of inputs) console.log(input.padEnd(44), await checkUrl(input));
})();
Name resolution is simulated with a lookup table, so the example is repeatable. In a real service, replace resolve() with dns.promises.lookup(host, { all: true }). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
https://schoolabe.com/image.png allowed (connect to 93.184.216.34)
http://127.0.0.1:6379/ rejected: 127.0.0.1 is a private address
http://0x7f.1/ rejected: 127.0.0.1 is a private address
http://2130706433/ rejected: 127.0.0.1 is a private address
http://169.254.169.254/latest/meta-data/ rejected: 169.254.169.254 is a private address
http://[::1]/admin rejected: ::1 is a private address
http://intranet.example/ rejected: 10.2.3.4 is a private address
http://sneaky.example/ rejected: 127.0.0.1 is a private address
http://schoolabe.com@127.0.0.1/ rejected: credentials in the URL
file:///etc/passwd rejected: protocol file:
ftp://schoolabe.com/file rejected: protocol ftp:
not a url rejected: not a valid URL
Key points
Allow only http and https. Parse before checking.
Resolve the name, and block private, loopback and link-local ranges.
Connect to the checked IP to stop DNS rebinding.
Handle redirects hop by hop.
Network isolation is the strongest layer.
Common mistakes
Checking the URL text with a regular expression instead of parsing it.
Resolving the name for the check and again for the connection.
Following redirects automatically.
Blocking only 127.0.0.1 and forgetting 169.254.169.254, IPv6 and private ranges.
Follow-ups
What is DNS rebinding?
How does IMDSv2 reduce the impact of SSRF?
How would you build an allow-list for a link preview feature?
Tips
List the defence layers in order and end with network isolation.
Mention the parser normalising odd IP spellings.
Name DNS rebinding and redirects.
85.nodejs-0085Mediummid
How do you build a TCP server and client with the net module, and what events matter?
net.createServer gives a handler that receives a socket for each client. A socket is a duplex stream: read with the 'data' event or pipe, write with socket.write. Key events are 'connection', 'data', 'end' (the other side finished sending), 'close' and 'error'. TCP is a byte stream, so message boundaries are not preserved.
Full answer
net is the low-level API under http and many databases. A TCP connection is a reliable, ordered, two-way stream of bytes.
Server side:
const server = net.createServer((socket) => { ... }); server.listen(port, host).
Each socket is a Duplex stream. socket.setEncoding('utf8') turns chunks into strings. socket.pipe(socket) makes an echo server.
server.close() stops accepting new connections and calls back when all existing ones end.
server.address() gives the actual port (use listen(0) in tests).
Client side: net.connect({ port, host }) or net.createConnection returns a socket. 'connect' fires when the connection is ready.
Events and behaviours:
'data': a chunk arrived. The chunk size is not tied to how the other side wrote. Two writes can arrive as one chunk, and one write as several.
'end': the other side called end() (half-close). By default Node then closes your side as well (allowHalfOpen: false).
'close': the connection is fully closed (hadError says whether an error caused it).
'error': always attach a handler. A reset by the peer (ECONNRESET) is common and, unhandled, crashes the process.
'timeout' with socket.setTimeout(ms): fires when idle. Then destroy the socket yourself.
Backpressure: socket.write returns false when the buffer is full. Wait for 'drain'.
socket.setKeepAlive and setNoDelay (disables Nagle's algorithm, useful for small latency-sensitive messages).
Since sockets are streams, pipeline, transforms and async iteration all work. Protocol design is your job: choose delimiters or length prefixes (see the framing question).
The server listens on port 0, so the system chooses a free port, and the order of the events shows the life of one connection. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
client: connected
client received: echo: HELLO NODE
server: client finished sending
server: connection closed
client: closed
server: stopped accepting and all connections are gone
Key points
Each connection gives a duplex socket stream.
'end' means the peer finished. 'close' means fully closed.
Always handle 'error' on sockets.
TCP does not keep message boundaries.
Common mistakes
Assuming one write on the client equals one 'data' event on the server.
Not handling 'error', so a reset connection crashes the process.
Never closing idle sockets.
Ignoring backpressure when sending large data.
Follow-ups
What is Nagle's algorithm and when do you disable it?
How does allowHalfOpen change the behaviour?
How would you limit the number of connections?
Tips
Say 'TCP is a stream, not messages' early.
Know the difference between end and close.
Mention listen(0) for tests.
86.nodejs-0086Mediummid
How does UDP differ from TCP, and how do you send and receive datagrams with the dgram module?
UDP sends independent packets (datagrams) with no connection, no delivery guarantee, no ordering and no retransmission, but with very low overhead and preserved message boundaries. In Node, dgram.createSocket('udp4') gives a socket that you bind, send(msg, port, host) on, and read with the 'message' event.
Full answer
TCP gives a reliable ordered byte stream. UDP gives much less, and that is the point:
No connection set-up. A sender just sends a packet to an address and port.
Message boundaries are kept: one send is one message at the receiver (if it arrives).
No guarantees: packets can be lost, duplicated or reordered. Nothing tells you.
Size limit: a datagram should fit the path MTU (about 1,200 to 1,472 bytes to be safe). Larger packets get fragmented, and the loss of a fragment loses the whole message. The hard limit is about 65,507 bytes.
No congestion control built in, so applications must be polite.
Good uses: DNS queries, real-time audio and video, game state, metrics (StatsD), service discovery, logging at high volume where a lost line is acceptable. Not for payments or files, unless a protocol on top adds acknowledgements and retries (as QUIC and some game protocols do).
socket.bind(port, address): needed to receive. A socket that only sends is bound automatically to a random port.
socket.on('message', (msg, rinfo)): msg is a Buffer and rinfo has address, port and size.
socket.send(msg, port, address, callback). With a connected socket (socket.connect) you can omit the address.
Broadcast (setBroadcast(true)) and multicast (addMembership) exist for local networks.
socket.close() when done. Remember to handle 'error'.
Because there are no acknowledgements, a sender cannot know whether the message arrived. If you need that, add sequence numbers and ACK messages, or use TCP.
javascript
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
const received = [];
server.on('message', (message, remote) => {
const text = message.toString();
received.push(text);
// Reply to the sender's address and port.
server.send('ack:' + text, remote.port, remote.address);
});
server.on('listening', () => {
const { port } = server.address();
const client = dgram.createSocket('udp4');
const replies = [];
client.on('message', (message) => {
replies.push(message.toString());
if (replies.length === 3) {
console.log('server received (each send is one message):', received);
console.log('client received:', replies);
console.log('message boundaries are kept: 3 sends -> 3 messages');
client.close();
server.close();
}
});
// Send one at a time on localhost so the order stays stable in this demo.
let i = 0;
const sendNext = () => {
client.send(Buffer.from('ping ' + ++i), port, '127.0.0.1', () => {
if (i < 3) setTimeout(sendNext, 5);
});
};
sendNext();
});
server.bind(0, '127.0.0.1');
On a real network, packets may be lost or arrive out of order. On localhost they almost never are, so the demo sends one packet at a time to keep the output identical on every run. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
server received (each send is one message): [ 'ping 1', 'ping 2', 'ping 3' ]
client received: [ 'ack:ping 1', 'ack:ping 2', 'ack:ping 3' ]
message boundaries are kept: 3 sends -> 3 messages
Key points
UDP is connectionless and unreliable, but keeps message boundaries.
Keep datagrams small, below the MTU.
Use it where speed matters more than every packet.
Reliability needs your own protocol.
Common mistakes
Using UDP and assuming delivery.
Sending datagrams larger than the MTU.
Forgetting to bind before expecting messages.
Not closing sockets, which keeps the process alive.
Follow-ups
How would you add reliability on top of UDP?
What is multicast and when is it used?
Why does DNS use UDP first and TCP as a fallback?
Tips
Compare TCP and UDP in a table-like sentence.
Say 'message boundaries are kept'.
Mention size limits.
87.nodejs-0087Mediummid
TCP has no message boundaries. How do you frame messages with a length prefix and handle partial chunks?
Because TCP is a byte stream, data events can contain half a message or several messages. Add a length header (for example 4 bytes, big-endian) before each message. The receiver keeps a buffer, reads the length, waits until enough bytes have arrived, emits the message and continues. Check the length against a maximum.
Full answer
When a client writes 'hello' and 'world' separately, the server may see 'helloworld' in one chunk, or 'hel' and 'loworld' in two. The operating system and the network decide. So the application protocol must mark where each message starts and ends.
Common methods:
Delimiter: end every message with a newline (\n). Simple, good for text, but the payload must not contain the delimiter (escape it, or use JSON lines).
Fixed length: every message has the same size. Wasteful and inflexible.
Length prefix: a header that holds the payload length, then the payload. Works for binary data of any content. Used by many databases and RPC protocols.
Decoder algorithm for a 4-byte big-endian length:
Append each new chunk to a buffer of pending bytes.
While the buffer has at least 4 bytes, read the length. If the buffer holds fewer than 4 + length bytes, stop and wait for more data.
Otherwise cut out the payload, emit it, and remove 4 + length bytes from the buffer.
Repeat, because one chunk may complete several messages.
Safety: validate the length. A hostile client can send 0xFFFFFFFF and make you wait for, or allocate, 4 GB. Set a maximum and destroy the connection when it is exceeded. Also set an idle timeout.
Implement the decoder as a Transform stream in object mode, so it fits pipelines and gets backpressure for free.
javascript
const net = require('node:net');
const { Transform } = require('node:stream');
const MAX_MESSAGE = 1024;
// Turns a stream of bytes into a stream of message strings.
class FrameDecoder extends Transform {
constructor() {
super({ readableObjectMode: true });
this.pending = Buffer.alloc(0);
}
_transform(chunk, encoding, callback) {
this.pending = Buffer.concat([this.pending, chunk]);
while (this.pending.length >= 4) {
const length = this.pending.readUInt32BE(0);
if (length > MAX_MESSAGE) return callback(new Error('message too large: ' + length));
if (this.pending.length < 4 + length) break; // wait for more bytes
this.push(this.pending.subarray(4, 4 + length).toString('utf8'));
this.pending = this.pending.subarray(4 + length);
}
callback();
}
}
function encode(text) {
const payload = Buffer.from(text, 'utf8');
const header = Buffer.alloc(4);
header.writeUInt32BE(payload.length);
return Buffer.concat([header, payload]);
}
// 1. Feed the decoder with awkward chunk boundaries.
const wire = Buffer.concat([encode('hello'), encode('नमस्ते'), encode('last')]);
const decoder = new FrameDecoder();
const messages = [];
decoder.on('data', (m) => messages.push(m));
let offset = 0;
for (const size of [1, 3, 2, 10, 5, 100]) {
decoder.write(wire.subarray(offset, offset + size));
offset += size;
}
decoder.end(wire.subarray(offset));
console.log('decoded from odd chunks:', messages);
// 2. The same decoder on a real TCP connection. The client sends all three frames in one write.
const server = net.createServer((socket) => {
const framed = socket.pipe(new FrameDecoder());
framed.on('data', (m) => console.log('server got message:', m));
framed.on('error', (err) => {
console.log('server rejects the connection:', err.message);
socket.destroy();
server.close();
});
});
server.listen(0, '127.0.0.1', () => {
const client = net.connect(server.address().port, '127.0.0.1', () => {
client.write(Buffer.concat([encode('one'), encode('two'), encode('three')]));
const evil = Buffer.alloc(4);
evil.writeUInt32BE(0xffffffff); // a hostile length (error on purpose)
setTimeout(() => client.end(evil), 20);
});
client.on('error', () => {});
client.on('close', () => {});
});
The last four bytes are a hostile length value (error on purpose). The decoder refuses it instead of waiting for 4 GB of data. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
decoded from odd chunks: [ 'hello', 'नमस्ते', 'last' ]
server got message: one
server got message: two
server got message: three
server rejects the connection: message too large: 4294967295
Key points
TCP delivers a byte stream, not messages.
A length prefix works for any binary payload.
The decoder buffers partial data and can emit several messages per chunk.
Enforce a maximum length.
Common mistakes
Assuming one data event is one message.
Trusting the length field without a maximum.
Converting each chunk to a string before the frame is complete, which breaks multi-byte characters.
Using string concatenation on a growing buffer for large streams.
Follow-ups
How would you frame messages in a text protocol?
How does HTTP mark the end of a body?
How would you add a message type and version to the header?
Tips
Describe the three framing methods in one line each.
Say 'partial reads' and 'several messages per chunk'.
Always mention the maximum length.
88.nodejs-0088Easyfresher
How do you compress and decompress data in Node.js with zlib (gzip, deflate, brotli), including streams?
zlib provides gzip, deflate and brotli. Use gzipSync and gunzipSync for small data, promisified functions for async work, and createGzip with pipeline for files and streams. Text such as JSON, HTML and logs compresses very well, while images and already compressed files do not.
Full answer
Compression trades CPU time for smaller data, which saves bandwidth and storage.
Formats in zlib:
gzip: the most common format (.gz files, HTTP Content-Encoding: gzip). Starts with the bytes 1f 8b.
deflate (and deflateRaw): the compression inside gzip with a smaller wrapper.
brotli: usually smaller than gzip for text, slower to compress at high levels. Supported by all modern browsers over HTTPS.
zstd support is arriving in newer Node versions, check the documentation for yours.
API styles:
Sync: zlib.gzipSync(buffer), gunzipSync. Blocks the event loop, so use only for small data or scripts.
Callback and promise: zlib.gzip(buffer, cb). Runs on the thread pool. util.promisify(zlib.gzip) gives a promise function.
Streams: zlib.createGzip(), createGunzip(), createBrotliCompress(). Combine with fs streams in stream.pipeline so memory stays small: pipeline(fs.createReadStream(a), zlib.createGzip(), fs.createWriteStream(a + '.gz')).
Options: level (1 fastest to 9 smallest, default 6 for gzip) and for brotli the params object (quality 0 to 11, default 11, which is slow; use 4 to 6 for dynamic responses).
Expect: JSON and text shrink by 70 to 90 percent. JPEG, PNG, MP4 and encrypted data shrink by almost nothing, and compressing them wastes CPU. Compress before encrypting, never after (encrypted data looks random).
Decompression of untrusted data needs limits, because small inputs can expand enormously (see the zip bomb question).
javascript
const zlib = require('node:zlib');
const { promisify } = require('node:util');
const { pipeline } = require('node:stream/promises');
const { Readable, Writable } = require('node:stream');
const gzip = promisify(zlib.gzip);
const gunzip = promisify(zlib.gunzip);
async function main() {
// Repetitive text, like a JSON report.
const text = JSON.stringify(Array.from({ length: 500 }, (_, i) => ({ id: i, status: 'present', subject: 'Maths' })));
const original = Buffer.from(text);
// 1. Sync and async give the same format.
const compressed = zlib.gzipSync(original);
console.log('original bytes > 10000:', original.length > 10000, '| gzip is smaller:', compressed.length < original.length / 5);
console.log('gzip magic bytes:', compressed.subarray(0, 2).toString('hex'));
console.log('round trip equal:', zlib.gunzipSync(compressed).equals(original));
console.log('async round trip equal:', (await gunzip(await gzip(original))).equals(original));
// 2. Brotli
const brotli = zlib.brotliCompressSync(original);
console.log('brotli round trip equal:', zlib.brotliDecompressSync(brotli).equals(original));
console.log('brotli is not larger than gzip for this text:', brotli.length <= compressed.length);
// 3. Streams: compress and decompress in a pipeline, in small chunks.
const chunks = [];
await pipeline(
Readable.from([original.subarray(0, 4000), original.subarray(4000)]),
zlib.createGzip({ level: 9 }),
zlib.createGunzip(),
new Writable({ write(chunk, enc, cb) { chunks.push(chunk); cb(); } }),
);
console.log('stream round trip equal:', Buffer.concat(chunks).equals(original));
// 4. Random bytes (like encrypted or already compressed data) do not shrink.
const random = require('node:crypto').randomBytes(10000);
console.log('random data is not smaller after gzip:', zlib.gzipSync(random).length >= random.length);
}
main();
The report has repeated text, which compresses well. Random bytes stand in for data that is already compressed or encrypted. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
original bytes > 10000: true | gzip is smaller: true
gzip magic bytes: 1f8b
round trip equal: true
async round trip equal: true
brotli round trip equal: true
brotli is not larger than gzip for this text: true
stream round trip equal: true
random data is not smaller after gzip: true
Key points
gzip, deflate and brotli are available.
Use streams and pipeline for files, sync only for small data.
Text compresses well, media does not.
Compress before encrypting.
Common mistakes
Using gzipSync inside a request handler for large bodies.
Compressing images, video or encrypted data.
Setting brotli quality 11 for dynamic responses.
Forgetting to handle errors on both the gzip and the file streams (use pipeline).
Follow-ups
Why compress before encrypting?
How does the thread pool relate to async zlib calls?
What is the difference between gzip and deflate?
Tips
Name three formats and when each is used.
State the stream pattern with pipeline.
Remember that media does not compress.
89.nodejs-0089Mediummid
How do you protect a server from decompression bombs, and how do you add gzip or brotli compression to HTTP responses correctly?
A zip bomb is a small compressed file that expands to gigabytes. Set maxOutputLength on zlib calls (or count bytes while streaming) to stop it. For HTTP, read Accept-Encoding, choose an encoding you support, set Content-Encoding and Vary: Accept-Encoding, skip tiny or already compressed responses, and compress with streams.
Full answer
Decompression bombs: 10 MB of zeros compresses to about 10 KB. A request with Content-Encoding: gzip, an uploaded archive or a gzipped log can therefore expand a thousand times or more. If the server inflates it in memory without a limit, a single request can exhaust memory.
Defences:
Sync and callback APIs accept { maxOutputLength: bytes }. When the limit is exceeded, they throw ERR_BUFFER_TOO_LARGE.
With streams, count the bytes that leave the decompressor in a Transform and destroy the pipeline when the total goes over the limit.
Limit the compressed input size too, and the compression ratio you accept.
Run with time limits and, for archives, limit the number of entries and the nesting depth.
Compressing HTTP responses:
Read req.headers['accept-encoding'] (for example 'gzip, deflate, br').
Pick an encoding you support. Prefer br for static text, gzip as the common fallback.
Set Content-Encoding to the choice and Vary: Accept-Encoding, so caches store the variants separately. Remove Content-Length (the compressed length is not known up front) or use chunked transfer.
Pipe the body through zlib.createGzip() (or createBrotliCompress with a moderate quality) into res. Use pipeline for error handling.
Do not compress small bodies (under about 1 KB) or types that are already compressed (images, video, zip, woff2).
For dynamic responses use a lower level or quality to save CPU. Pre-compress static assets at build time or let a reverse proxy or CDN do it.
Security note: compressing secrets together with attacker-controlled text in the same response can leak the secret by response size (the BREACH attack). Avoid reflecting user input next to tokens in compressed pages, and use per-request token masking.
javascript
const zlib = require('node:zlib');
const http = require('node:http');
// 1. A small file that expands a lot: 20 MB of zeros.
const bomb = zlib.gzipSync(Buffer.alloc(20 * 1024 * 1024));
console.log('compressed size is under 100 KB:', bomb.length < 100 * 1024);
try {
zlib.gunzipSync(bomb, { maxOutputLength: 1024 * 1024 }); // allow at most 1 MB
} catch (err) {
console.log('decompression stopped:', err.code); // (error on purpose)
}
console.log('with a high enough limit it works:', zlib.gunzipSync(bomb, { maxOutputLength: 32 * 1024 * 1024 }).length);
// 2. Content negotiation for an HTTP response.
const body = Buffer.from('<li>Student record</li>'.repeat(2000));
const server = http.createServer((req, res) => {
const accepted = String(req.headers['accept-encoding'] || '');
res.setHeader('Content-Type', 'text/html');
res.setHeader('Vary', 'Accept-Encoding');
if (accepted.includes('gzip')) {
res.setHeader('Content-Encoding', 'gzip');
res.end(zlib.gzipSync(body)); // for big or dynamic bodies use streams with pipeline
} else {
res.end(body);
}
});
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
// Use the raw http module so the response bytes are not decompressed for us.
const get = (headers) => new Promise((resolve) => {
http.get(base, { headers }, (res) => {
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ encoding: res.headers['content-encoding'] || 'none', vary: res.headers.vary, size: Buffer.concat(chunks).length }));
});
});
const plain = await get({ 'Accept-Encoding': 'identity' });
const packed = await get({ 'Accept-Encoding': 'gzip, deflate' });
console.log('without gzip:', plain.encoding, '| same size as the body:', plain.size === body.length);
console.log('with gzip:', packed.encoding, '| vary:', packed.vary, '| much smaller:', packed.size < body.length / 10);
server.close();
});
The first limit check fails on purpose (error on purpose) to show ERR_BUFFER_TOO_LARGE. The HTTP part uses the raw http client so the compressed bytes can be measured. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
compressed size is under 100 KB: true
decompression stopped: ERR_BUFFER_TOO_LARGE
with a high enough limit it works: 20971520
without gzip: none | same size as the body: true
with gzip: gzip | vary: Accept-Encoding | much smaller: true
Key points
maxOutputLength stops decompression bombs.
Count bytes in streams and abort on excess.
Content-Encoding plus Vary: Accept-Encoding for responses.
Skip small and already compressed content.
Pre-compress static files or use a proxy.
Common mistakes
Inflating uploaded or request data with no output limit.
Forgetting the Vary header, so a cache serves gzip to a client that cannot read it.
Compressing small or already compressed responses.
Compressing responses that mix secrets and user-controlled text.
Follow-ups
How would you limit decompression in a stream?
What does the BREACH attack exploit?
Where should compression happen: Node, a proxy or a CDN?
Tips
Say 'maxOutputLength' for the bomb question.
List the response steps: negotiate, headers, stream.
Mention that proxies and CDNs usually compress static assets better.
90.nodejs-0090Easyfresher
How do you build interactive prompts with readline/promises, and what goes wrong with piped input?
readline/promises gives rl.question(prompt) that resolves with the user's answer. Create the interface with process.stdin and process.stdout, close it when done, and pass an AbortSignal to stop waiting. When input is piped and ends before you ask the next question, the interface closes, so use for await over the lines for piped or scripted input.
Full answer
The readline module reads input one line at a time from any readable stream, most often process.stdin.
rl.question(text, { signal }) shows the prompt and resolves with the line. An AbortSignal (for example AbortSignal.timeout(10000)) cancels it.
rl.on('line', fn) fires for every line, with rl.setPrompt() and rl.prompt() for a loop-style shell (a REPL).
for await (const line of rl) reads all lines until the input ends. This is the right tool for piped input such as cat data.txt | node app.js.
rl.on('close') fires on Ctrl+D, Ctrl+C or when the input ends. Always close the interface, or the process waits for stdin forever.
history, tab completion (completer function) and line editing work when the input is a terminal. process.stdin.isTTY tells you whether it is one.
Passwords: readline does not hide typed characters by default. Use a muted output stream or a library for secret input.
The piped input trap: if input is a file or pipe, all lines can arrive before your code asks a question. Lines that arrive when no question is waiting are not kept for later. When the input then ends, the interface closes, and the next question() throws ERR_USE_AFTER_CLOSE. So interactive scripts that should also accept piped data must read lines with for await, or check isTTY and choose a mode.
For testing, give createInterface a PassThrough stream as input and a Writable as output, and feed the answers from the test.
javascript
const readline = require('node:readline/promises');
const { PassThrough, Writable, Readable } = require('node:stream');
async function main() {
// 1. A scripted conversation: the "user" answers each prompt after it appears.
const input = new PassThrough();
const shown = [];
const output = new Writable({ write(chunk, enc, cb) { shown.push(chunk.toString()); cb(); } });
const rl = readline.createInterface({ input, output, terminal: false });
const ask = (prompt, answer) => {
const pending = rl.question(prompt);
input.write(answer + '\n');
return pending;
};
const name = await ask('Name? ', 'Asha');
const marks = Number(await ask('Marks? ', '78'));
rl.close();
console.log('prompts shown:', shown);
console.log('answers:', { name, marks });
// 2. Cancel a question that gets no answer.
const quiet = readline.createInterface({ input: new PassThrough(), output, terminal: false });
const giveUp = new AbortController();
setTimeout(() => giveUp.abort(), 20); // a normal timer keeps the process alive while we wait
await quiet.question('Anyone there? ', { signal: giveUp.signal })
.catch((err) => console.log('question cancelled by:', err.name));
quiet.close();
// 3. Piped input: read every line with for await.
const piped = readline.createInterface({ input: Readable.from(['10\n', '20\n', '30\n']), terminal: false });
let total = 0;
for await (const line of piped) total += Number(line);
console.log('sum of piped lines:', total);
// 4. The trap: asking a question after piped input has ended.
const late = readline.createInterface({ input: Readable.from(['only line\n']), output, terminal: false });
await new Promise((resolve) => late.once('close', resolve));
await late.question('Another one? ').catch((err) => console.log('question after close:', err.code)); // (error on purpose)
}
main();
The output stream is a Writable that collects the prompts, so the example runs without a keyboard. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
prompts shown: [ 'Name? ', 'Marks? ' ]
answers: { name: 'Asha', marks: 78 }
question cancelled by: AbortError
sum of piped lines: 60
question after close: ERR_USE_AFTER_CLOSE
Key points
rl.question gives a promise of one answer.
Close the interface, or the process may not exit.
Piped input needs for await, not a question loop.
Use a PassThrough input to test prompts.
Common mistakes
Forgetting rl.close(), so the script never exits.
Using a question loop on piped input.
Expecting readline to hide a typed password.
Mixing readline and direct process.stdin listeners on the same stream.
Follow-ups
How would you build a small REPL with a custom prompt?
How do you detect that input comes from a pipe?
How does tab completion work with a completer function?
Tips
Mention close() before anything else.
Show you know the piped input trap.
Say that for await is the pipe-safe way.
91.nodejs-0091Mediummid
What is AsyncLocalStorage, and how do you use it to keep a request id available across async calls?
AsyncLocalStorage stores a value for the duration of an asynchronous operation chain. als.run(store, fn) makes the store available to fn and to everything it starts through promises, timers and callbacks, and als.getStore() reads it anywhere in that chain. It carries a request id or user without passing parameters through every function.
Full answer
Problem: a log line deep in the code should show the request id, but the id enters at the HTTP handler, and ten functions and several awaits lie between. Passing a context argument through every function is noisy. Global variables break, because concurrent requests overwrite each other.
AsyncLocalStorage (from node:async_hooks) solves this. It works like thread-local storage, but for asynchronous call chains:
const als = new AsyncLocalStorage();
als.run({ requestId: 'r1' }, () => { ... }); // everything started inside sees this store
als.getStore(); // returns the store, or undefined outside a run
How it works: Node tracks which asynchronous resource (promise, timer, socket callback) was created while which store was active, and restores that store when the callback runs. So the store follows await, setTimeout, process.nextTick, fs callbacks and most I/O.
Typical uses: request ids and trace ids for logs, the current user or tenant, per-request database transactions, timing and metrics, feature flags per request.
Rules:
Call als.run at the entry point (middleware), once per request.
Each run gets its own store, so concurrent requests stay separate.
Store small objects. Mutating the store object is visible to everything inside the same run.
als.getStore() returns undefined outside a run, so code must handle that (for example in start-up code or tests).
Performance cost is small on current Node versions, but not zero. Do not use it for things you could pass as a plain argument in a small code base.
Frameworks use it internally for the same purpose, and OpenTelemetry context propagation is built on it.
javascript
const http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');
const context = new AsyncLocalStorage();
const logLines = [];
// A logger that needs no request argument.
function log(message) {
const store = context.getStore();
logLines.push(`[${store ? store.requestId : 'no request'}] ${message}`);
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function loadMarks(studentId) {
log('loading marks for ' + studentId);
await wait(studentId === 1 ? 30 : 10); // the two requests finish in a different order
log('marks loaded for ' + studentId);
return 70 + studentId;
}
let counter = 0;
const server = http.createServer((req, res) => {
const store = { requestId: 'req-' + ++counter };
context.run(store, async () => {
log('request started: ' + req.url);
const studentId = Number(req.url.slice(1));
const marks = await loadMarks(studentId);
setTimeout(() => { log('response sent'); res.end(String(marks)); }, 5); // a timer keeps the store too
});
});
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
// Two overlapping requests.
const [a, b] = await Promise.all([fetch(base + '/1'), fetch(base + '/2')]);
console.log('responses:', await a.text(), await b.text());
const byRequest = {};
for (const line of logLines) {
const id = line.slice(1, line.indexOf(']'));
(byRequest[id] ||= []).push(line.slice(line.indexOf(']') + 2));
}
for (const id of Object.keys(byRequest).sort()) console.log(id, '->', byRequest[id].join(' | '));
log('outside any request');
console.log('last line:', logLines.at(-1));
server.close();
});
Although the two requests overlap and finish in a different order, each keeps its own log lines because each has its own store. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
responses: 71 72
req-1 -> request started: /1 | loading marks for 1 | marks loaded for 1 | response sent
req-2 -> request started: /2 | loading marks for 2 | marks loaded for 2 | response sent
last line: [no request] outside any request
Key points
als.run(store, fn) sets the context. getStore() reads it.
The store follows promises, timers and callbacks.
Each request gets its own run.
getStore() is undefined outside a run.
Common mistakes
Using a module-level variable for the request id.
Calling getStore() in start-up code and assuming a value.
Forgetting that the store object is shared by reference inside one run.
Calling als.run in many nested places and creating confusing contexts.
Follow-ups
How do you add the request id to every log line automatically?
What is the performance cost?
How does OpenTelemetry use this mechanism?
Tips
Open with the problem: passing context through ten functions.
Say 'follows await, timers and callbacks'.
Mention one store per request.
92.nodejs-0092Hardsenior
When does AsyncLocalStorage lose context, and how do AsyncResource, bind and snapshot fix it?
Context follows the asynchronous resource that was created inside run(). It is lost or wrong when work is queued and executed later by shared code (a connection pool, a job queue, an event emitter listener registered elsewhere). Capture the context when you queue the work with AsyncLocalStorage.bind, AsyncResource.bind or AsyncLocalStorage.snapshot, and restore it when the work runs.
Full answer
AsyncLocalStorage attaches the store to async resources as they are created. That works for promises, timers and most I/O. Problems appear when the code that runs a callback is not in the same context as the code that scheduled it.
Typical cases:
EventEmitter listeners. A listener runs in the context of the code that calls emit(), not the code that called on(). A listener added during request A but triggered during request B sees B's store.
Pools and queues. A connection pool or job queue starts its worker loop once, in some context. Callbacks queued later by many requests run in the loop's context (often none), and the request's store is gone.
Callback APIs of libraries that keep their own queue of callbacks and call them later.
als.enterWith(store): sets the store for the rest of the current execution without a run() scope. It is easy to leak into unrelated code, so prefer run().
Fixes:
AsyncLocalStorage.bind(fn): returns a function that always runs in the context captured when bind was called.
AsyncLocalStorage.snapshot(): captures all active contexts and returns a runner (runInAsyncScope style) function. Good for queues: take the snapshot when enqueuing, call snapshot(fn) when executing.
AsyncResource: new AsyncResource('JobQueue') captures the current context, and resource.runInAsyncScope(fn) or AsyncResource.bind(fn) runs inside it. This is what library authors use.
als.exit(fn) runs fn with no store, useful for background work that should not inherit the request.
Design advice: capture context at the boundary where work leaves the request (enqueue, add listener), not inside the library. Test with two overlapping requests, as one request alone hides most problems.
javascript
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
const { EventEmitter } = require('node:events');
const als = new AsyncLocalStorage();
const who = () => als.getStore()?.user ?? 'nobody';
// 1. EventEmitter: the listener sees the context of emit(), not of on().
const events = new EventEmitter();
als.run({ user: 'Asha' }, () => {
events.on('result', () => console.log('1. plain listener sees:', who()));
events.on('result', AsyncLocalStorage.bind(() => console.log('1. bound listener sees:', who())));
});
als.run({ user: 'Ravi' }, () => events.emit('result')); // triggered in Ravi's request
// 2. exit(): run without the store
als.run({ user: 'Zoya' }, () => {
console.log('2. before exit:', who());
als.exit(() => console.log('2. inside exit:', who()));
});
// 3. A shared queue that runs jobs later, from its own loop.
const queue = [];
const enqueue = (job) => queue.push(job);
als.run({ user: 'Meera' }, () => {
enqueue(() => console.log('3. job without capture sees:', who()));
enqueue(AsyncLocalStorage.bind(() => console.log('3. job with bind sees: ', who())));
const snapshot = AsyncLocalStorage.snapshot();
enqueue(() => snapshot(() => console.log('3. job with snapshot sees:', who())));
});
setImmediate(() => { while (queue.length) queue.shift()(); }); // the queue loop starts outside any request
// 4. AsyncResource: capture once, run many times.
let resource;
als.run({ user: 'Kabir' }, () => { resource = new AsyncResource('ReportJob'); });
setTimeout(() => {
console.log('4. outside:', who());
resource.runInAsyncScope(() => console.log('4. inside the captured resource:', who()));
}, 10);
The plain listener and the plain job show the wrong or missing user. The bound versions restore the context captured when the work was queued. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
1. plain listener sees: Ravi
1. bound listener sees: Asha
2. before exit: Zoya
2. inside exit: nobody
3. job without capture sees: nobody
3. job with bind sees: Meera
3. job with snapshot sees: Meera
4. outside: nobody
4. inside the captured resource: Kabir
Key points
Context follows creation, not execution, for async resources.
emit() runs listeners in the emitter's calling context.
Queues and pools need the context captured when work is added.
Use bind, snapshot or AsyncResource to restore it.
Prefer run() over enterWith().
Common mistakes
Assuming a listener runs in the context where it was registered.
Using enterWith() in a shared function.
Testing with only one request at a time.
Capturing context inside the queue library instead of at the call site.
Follow-ups
How does als.run differ from enterWith?
How would you propagate the context into a worker thread?
What does a library need to do to support ALS in its pool?
Tips
Say 'creation context, not execution context'.
Offer the three fixes and when each fits.
Mention testing with overlapping requests.
93.nodejs-0093Hardsenior
What is the diagnostics_channel module, and how do libraries and monitoring tools use it?
diagnostics_channel is a built-in publish and subscribe system for diagnostic events. A library publishes messages on a named channel, and tools subscribe without patching the library. It costs almost nothing when nobody subscribes. TracingChannel adds standard start, end, asyncStart, asyncEnd and error events around an operation.
Full answer
Monitoring tools (APM, tracing, profilers) used to wrap library functions at run time ("monkey patching") to learn about requests and queries. That is fragile. diagnostics_channel gives a clean contract: the library says "something happened" on a named channel, and anyone interested listens.
Core API:
const ch = diagnostics_channel.channel('my-lib:query'): get a channel by name. Names are global strings, so use a prefix.
ch.publish(message): send an object to subscribers. Check ch.hasSubscribers first, so building the message costs nothing when nobody listens.
diagnostics_channel.subscribe(name, handler) or ch.subscribe(handler): listen. Handlers run synchronously inside publish(), so they must be fast and must not throw into the caller.
channel.bindStore(als, transform) connects a channel to an AsyncLocalStorage, so a store is set around a traced operation.
TracingChannel (diagnostics_channel.tracingChannel(name)) models an operation with a lifecycle:
tracePromise(fn, context), traceSync, traceCallback run the function and publish: start (before), end (sync part finished), asyncStart and asyncEnd (promise settled), and error. The same context object is passed through all events, so a subscriber can store the start time on it and compute the duration in asyncEnd.
Node core publishes channels such as http.client.request.start, http.server.request.start, net.client.socket, undici:request:create and others. Libraries such as undici, and database drivers, publish their own. OpenTelemetry instrumentations can subscribe instead of patching.
Guidelines for library authors: publish stable, documented messages; avoid heavy work when there are no subscribers; never let a subscriber failure break the library call.
The module is marked as experimental in parts of the API, so check the Node documentation for the version you use.
javascript
const dc = require('node:diagnostics_channel');
const { performance } = require('node:perf_hooks');
// --- A "library" that publishes events -------------------------------------
const queries = dc.tracingChannel('marks-db:query');
async function runQuery(sql) {
// Wrap the real work. The same context object travels through all events.
return queries.tracePromise(async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
if (sql.includes('broken')) throw new Error('syntax error near "broken"');
return [{ student: 'Asha', marks: 78 }];
}, { sql });
}
// A simple custom channel too.
const cacheChannel = dc.channel('marks-db:cache');
function cacheLookup(key) {
if (cacheChannel.hasSubscribers) cacheChannel.publish({ key, hit: key === 'known' }); // free when nobody listens
return key === 'known';
}
// --- A "monitoring tool" that subscribes, without touching the library -----
const seen = [];
queries.subscribe({
start(message) { message.startedAt = performance.now(); seen.push('start: ' + message.sql); },
end() { seen.push('end (synchronous part finished)'); },
asyncStart(message) { seen.push('asyncStart: ' + JSON.stringify(message.result)); },
asyncEnd(message) { seen.push('asyncEnd: took at least 10 ms = ' + (performance.now() - message.startedAt >= 9)); },
error(message) { seen.push('error: ' + message.error.message); },
});
dc.subscribe('marks-db:cache', (message) => seen.push('cache: ' + JSON.stringify(message)));
async function main() {
cacheLookup('before-subscription-check');
console.log('cache channel has subscribers:', cacheChannel.hasSubscribers);
cacheLookup('known');
await runQuery('SELECT * FROM marks');
await runQuery('SELECT broken').catch(() => {});
console.log(seen.join('\n'));
}
main();
The subscriber measures the duration by adding startedAt to the context object that is shared between the events. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
cache channel has subscribers: true
cache: {"key":"before-subscription-check","hit":false}
cache: {"key":"known","hit":true}
start: SELECT * FROM marks
end (synchronous part finished)
asyncStart: [{"student":"Asha","marks":78}]
asyncEnd: took at least 10 ms = true
start: SELECT broken
end (synchronous part finished)
error: syntax error near "broken"
asyncStart: undefined
asyncEnd: took at least 10 ms = true
Key points
Named channels give publish and subscribe for diagnostics.
Check hasSubscribers so unused channels cost nothing.
TracingChannel adds start, end, asyncStart, asyncEnd and error events.
Tools subscribe instead of monkey patching.
Common mistakes
Doing slow or blocking work inside a subscriber.
Building expensive messages without checking hasSubscribers.
Letting a subscriber throw into the library code.
Choosing channel names without a prefix and clashing with other libraries.
Follow-ups
How would you connect a channel to AsyncLocalStorage?
Which core modules publish diagnostics channels?
How does this differ from OpenTelemetry?
Tips
Contrast with monkey patching in the first sentence.
Know hasSubscribers.
List the five tracing events.
94.nodejs-0094Hardsenior
What is the Node.js permission model, and how do you restrict file system, child process and worker access?
Running node with --permission turns on a deny-by-default mode. Access to the file system, child processes, worker threads, native addons and WASI must be granted with flags such as --allow-fs-read=/data, --allow-fs-write=/tmp, --allow-child-process and --allow-worker. Blocked calls throw ERR_ACCESS_DENIED, and process.permission.has() checks a grant at run time.
Full answer
By default a Node program can do everything the user can: read any file, run any command, open any network connection. A bug or a malicious dependency then has the same power. The permission model is a way to apply the principle of least privilege to the process itself.
Using it: node --permission app.js. With no other flags the process may not read or write files (beyond what Node needs to start), spawn processes, create workers, load native addons or use WASI. Add grants:
--allow-fs-read=<path or pattern> and --allow-fs-write=<path>. Use * for all (not recommended). Paths can be repeated or comma separated.
--allow-child-process: allow child_process spawn, exec and fork.
--allow-worker: allow worker_threads.
--allow-addons and --allow-wasi.
Newer versions add network flags; check the documentation for the version you run.
Behaviour: a denied operation throws an error with code ERR_ACCESS_DENIED, and the error shows which permission and resource were refused. At run time, process.permission.has('fs.read', '/data') returns true or false, so code can adapt.
Limits to understand:
It is a safety net against accidents and some attacks, not a full sandbox. A process with child-process permission, or with write access to its own code, can escape. Treat the grants as part of a defence in depth.
It does not stop network access in older versions, and it does not restrict CPU or memory.
Permissions are inherited as set at start-up. They cannot be widened later.
Some patterns need extra care: the entry script and dependency folders must be readable for the app to start.
Good uses: running build scripts or third-party code with narrow rights, tools that process untrusted files, and hardening production services that know exactly which folders they use. Combine with containers, read-only file systems and OS users.
The child starts with --permission and read access to one folder only, so writing, the second folder and spawning processes are refused. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
read allowed file -> public notes
read forbidden file -> blocked with ERR_ACCESS_DENIED
write in allowed folder -> blocked with ERR_ACCESS_DENIED
start a child process -> blocked with ERR_ACCESS_DENIED
process.permission.has(fs.read, allowed): true
process.permission.has(fs.write, allowed): false
process.permission.has(child): false
child exit code: 0
Key points
--permission makes Node deny by default.
Grant only needed paths with --allow-fs-read and --allow-fs-write.
Denied calls throw ERR_ACCESS_DENIED.
process.permission.has checks a grant.
It is defence in depth, not a complete sandbox.
Common mistakes
Believing the permission model replaces containers.
Granting --allow-fs-read=* and gaining nothing.
Forgetting that the app needs read access to its own code and dependencies.
Allowing child processes and thinking the sandbox still holds.
Follow-ups
How is this different from Deno permissions?
How would you run an npm build script with minimal rights?
What does ERR_ACCESS_DENIED tell you?
Tips
Say 'deny by default' and 'least privilege'.
Name the flags for fs, child process and worker.
State clearly that it is not a full sandbox.
95.nodejs-0095Mediummid
How does the built-in fetch work in Node.js, and what are the common mistakes with status codes, timeouts and bodies?
Node has the standard fetch, Request, Response and Headers globals. fetch resolves with a Response even for 404 and 500, and rejects only on network failures, so you must check response.ok. A body can be read once, as json(), text() or a stream. Set a timeout with AbortSignal.timeout, because fetch has no default timeout.
Full answer
Since Node 18, fetch is a global function, and it is stable in current versions. It is implemented by undici and follows the browser API, so the same code runs on the server and in the browser.
Key behaviours:
fetch(url, options) returns a promise of a Response. It rejects (TypeError: fetch failed, with a cause such as ECONNREFUSED) when the request could not be made. A 404 or 500 is a normal resolved response. Check response.ok or response.status.
Reading the body: await response.json(), text(), arrayBuffer(), blob() or formData(). The body can be consumed once. Use response.clone() if you need two reads.
Streaming: response.body is a web ReadableStream. for await (const chunk of response.body) works, and Readable.fromWeb(response.body) converts it to a Node stream.
Sending: method, headers and body. For JSON: body: JSON.stringify(data) and a Content-Type: application/json header (fetch does not add it for strings). FormData and URLSearchParams set their own content type.
Timeouts and cancellation: signal: AbortSignal.timeout(5000). Without it a hung server can wait for a long time (the default header timeout is 5 minutes in undici).
Redirects are followed by default (redirect: 'follow'). Use 'manual' to inspect them, for example in SSRF protection.
Cookies are not stored (no cookie jar), and there is no CORS in Node.
Errors: add the URL and the status to the error you throw, and avoid logging full headers (they may contain tokens).
A small wrapper that sets a timeout, checks ok, and parses JSON with a clear error type removes most mistakes.
javascript
const http = require('node:http');
const server = http.createServer((req, res) => {
if (req.url === '/marks/1') {
res.setHeader('Content-Type', 'application/json');
return res.end(JSON.stringify({ id: 1, marks: 78 }));
}
if (req.url === '/slow') return; // never answers
if (req.method === 'POST') {
let body = '';
req.on('data', (c) => (body += c));
return req.on('end', () => res.end(JSON.stringify({ receivedType: req.headers['content-type'], body })));
}
res.statusCode = 404;
res.end('no such route');
});
async function getJson(url, options = {}) {
const response = await fetch(url, { signal: AbortSignal.timeout(100), ...options });
if (!response.ok) throw new Error(`HTTP ${response.status} for ${new URL(url).pathname}`);
return response.json();
}
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
// A port where nothing listens: open a server, note its port, close it again.
const probe = require('node:net').createServer();
await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve));
const closedUrl = 'http://127.0.0.1:' + probe.address().port + '/';
await new Promise((resolve) => probe.close(resolve));
console.log('GET json:', await getJson(base + '/marks/1'));
const missing = await fetch(base + '/nope'); // resolves, even though it is a 404
console.log('404 does not reject: ok =', missing.ok, '| status =', missing.status, '| text =', await missing.text());
await getJson(base + '/nope').catch((err) => console.log('wrapper throws:', err.message));
await getJson(base + '/slow').catch((err) => console.log('slow server:', err.name));
await fetch(closedUrl).catch((err) => console.log('connection refused:', err.name + ':', err.message, '| cause code:', err.cause?.code ?? err.cause?.errors?.[0]?.code));
const res = await fetch(base + '/marks/1');
await res.text();
await res.text().catch((err) => console.log('second read:', err.name));
const post = await fetch(base, { method: 'POST', body: JSON.stringify({ name: 'Asha' }), headers: { 'Content-Type': 'application/json' } });
console.log('POST echo:', await post.json());
const noHeader = await fetch(base, { method: 'POST', body: JSON.stringify({ name: 'Asha' }) });
console.log('content type when the header is missing:', (await noHeader.json()).receivedType);
server.closeAllConnections();
server.close();
});
The server never answers /slow, so the 100 ms timeout fires. A port where no server listens refuses the connection, which shows the other kind of failure. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
GET json: { id: 1, marks: 78 }
404 does not reject: ok = false | status = 404 | text = no such route
wrapper throws: HTTP 404 for /nope
slow server: TimeoutError
connection refused: TypeError: fetch failed | cause code: ECONNREFUSED
second read: TypeError
POST echo: { receivedType: 'application/json', body: '{"name":"Asha"}' }
content type when the header is missing: text/plain;charset=UTF-8
Key points
fetch rejects on network failure, not on 404 or 500.
Check response.ok.
The body can be read once.
Set a timeout with AbortSignal.timeout.
JSON requests need the Content-Type header.
Common mistakes
Assuming a 404 or 500 makes fetch reject.
Calling response.json() twice.
Posting JSON without the Content-Type header.
Using fetch without any timeout.
Follow-ups
How would you add retries to fetch?
How do you stream a large download to a file?
Why does the built-in fetch not send cookies automatically?
Tips
Lead with 'fetch resolves for 404'.
Mention AbortSignal.timeout.
Add that undici is the engine behind it.
96.nodejs-0096Hardsenior
How do you tune HTTP connections with undici (Agent, pool, keep-alive), and how do you mock HTTP calls in tests with MockAgent?
undici is the HTTP client behind Node's fetch. An Agent manages connection pools per origin, with options such as connections (the limit of sockets per origin), pipelining and keepAliveTimeout. Reusing connections avoids repeated TCP and TLS set-up. MockAgent intercepts requests by origin and path and replies with fake responses, with no network at all.
Full answer
Opening a connection costs a round trip for TCP and more for TLS. A service that calls other services should reuse connections and limit them.
undici concepts:
Dispatcher: the object that sends requests. Client (one connection), Pool (several connections to one origin), Agent (a pool per origin), ProxyAgent, MockAgent.
Agent options: connections (maximum sockets per origin), pipelining (requests sent on one connection before the response; the default is 1, which is safe), keepAliveTimeout, headersTimeout, bodyTimeout, connect options such as timeout.
undici.request(url, { dispatcher }) is the fastest, lowest-level API. undici.fetch is the standard API. You must always consume or destroy the response body (await body.text()), or the connection stays blocked.
setGlobalDispatcher(agent) changes the dispatcher used for requests. Check that your undici version matches the one inside Node when you pass a dispatcher from the npm package to the built-in global fetch, because a version mismatch can fail. Using undici.fetch from the same package avoids this.
Close agents on shutdown: await agent.close().
Why limits matter: with no limit, a burst of 10,000 calls to one host opens thousands of sockets and can overload both sides. With connections: 10 the extra requests queue inside the agent.
Testing: MockAgent replaces the network.
const mock = new MockAgent(); mock.disableNetConnect() makes any unmocked request fail, which catches accidental real calls.
Pass dispatcher: mock to the call (or set it as the global dispatcher).
Use .times(n), .persist(), delay(), and replyWithError() to test retries and timeouts.
This keeps unit tests fast and independent from real services.
javascript
const http = require('node:http');
const { Agent, MockAgent, request, fetch: undiciFetch } = require('undici');
async function main() {
// A local server that counts how many TCP connections it receives.
let sockets = 0;
const server = http.createServer((req, res) => setTimeout(() => res.end('ok'), 10));
server.on('connection', () => sockets++);
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const url = 'http://127.0.0.1:' + server.address().port;
// 1. One connection is reused for sequential requests.
const oneConnection = new Agent({ connections: 1, keepAliveTimeout: 1000 });
for (let i = 0; i < 5; i++) {
const { body } = await request(url, { dispatcher: oneConnection });
await body.text(); // always read the body, so the connection is free again
}
console.log('5 sequential requests used', sockets, 'connection(s)');
// 2. The pool never opens more connections than the limit.
sockets = 0;
const twoConnections = new Agent({ connections: 2 });
await Promise.all(Array.from({ length: 6 }, async () => {
const { body } = await request(url, { dispatcher: twoConnections });
await body.text();
}));
console.log('6 parallel requests with connections: 2 used', sockets, 'connections');
await oneConnection.close();
await twoConnections.close();
server.close();
// 3. MockAgent: no network at all.
const mock = new MockAgent();
mock.disableNetConnect();
mock.get('https://api.example.com')
.intercept({ path: '/marks/1', method: 'GET' })
.reply(200, { id: 1, marks: 78 }, { headers: { 'content-type': 'application/json' } });
mock.get('https://api.example.com')
.intercept({ path: '/flaky', method: 'GET' })
.replyWithError(new Error('socket hang up'));
const ok = await undiciFetch('https://api.example.com/marks/1', { dispatcher: mock });
console.log('mocked response:', ok.status, await ok.json());
await undiciFetch('https://api.example.com/flaky', { dispatcher: mock }).catch((err) => console.log('mocked failure:', err.cause.message));
await undiciFetch('https://api.example.com/not-mocked', { dispatcher: mock }).catch((err) => console.log('unmocked call is blocked:', err.cause.code));
await mock.close();
}
main();
On the versions used here (undici 8.14.0 on Node 24.22.1), passing the npm Agent to the built-in global fetch failed with an invalid argument error, so the example uses undici's own fetch and request. Install first with npm install undici (run here with undici 8.14.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
5 sequential requests used 1 connection(s)
6 parallel requests with connections: 2 used 2 connections
mocked response: 200 { id: 1, marks: 78 }
mocked failure: socket hang up
unmocked call is blocked: UND_MOCK_ERR_MOCK_NOT_MATCHED
Key points
Agent keeps pools per origin. connections limits the sockets.
Always consume the response body.
Reusing connections saves TCP and TLS set-up.
MockAgent plus disableNetConnect gives network-free tests.
Close agents on shutdown.
Common mistakes
Not reading the response body, so the connection never returns to the pool.
Creating a new Agent for every request.
Passing a dispatcher from a different undici version to the global fetch.
Running tests that call real services.
Follow-ups
What does pipelining change, and why is it risky?
How would you set different limits for different origins?
How do you test a retry with MockAgent?
Tips
Explain the cost of new connections in one sentence.
Say 'consume the body'.
Mention disableNetConnect for tests.
97.nodejs-0097Mediummid
What does a good Dockerfile for a Node.js service look like, and why does PID 1 and signal handling matter?
Use a small official Node image with a fixed version, copy package files first so dependency installation is cached, run npm ci with only production dependencies, run as the non-root node user, set NODE_ENV=production, add a health check, and start with node directly (not through npm), so SIGTERM reaches the app. Use an init process or handle signals in code, because PID 1 behaves differently.
Full answer
A reasonable multi-stage Dockerfile (written for explanation; it was not built on this box, which has no Docker):
FROM node:24-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
Pin the image version (node:24-slim or a digest), not latest, so builds repeat.
Copy package files before the source so Docker reuses the cached dependency layer until package.json changes.
npm ci uses the lock file and gives repeatable installs. --omit=dev leaves out test and build tools, which makes the image smaller and safer.
A .dockerignore (node_modules, .git, .env, logs) keeps secrets and junk out of the build context.
USER node: do not run as root. A bug then has fewer rights.
NODE_ENV=production switches libraries to their production behaviour.
Never bake secrets into the image. Pass them at run time as environment variables or mounted secrets.
PID 1 and signals: docker stop sends SIGTERM to the process with PID 1 in the container. If you start the app with npm start, npm (or a shell) is PID 1 and may not forward the signal, so the app is killed hard after the timeout (10 seconds by default). Use CMD ["node", "server.js"] in exec form. Also, on Linux PID 1 has no default signal handlers, so a Node process as PID 1 ignores SIGTERM unless the code registers a handler. Handle SIGTERM in code (graceful shutdown) or add a tiny init such as tini (docker run --init).
Other points: write logs to stdout, set memory limits and make Node aware of them (--max-old-space-size or the default container awareness in current Node), and use a health check that tests the app, not only the process.
javascript
const { spawn, 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(), 'docker-demo-'));
// The service: /health answers 200 and the app stops cleanly on SIGTERM.
fs.writeFileSync(path.join(dir, 'server.js'), `
const http = require('node:http');
const server = http.createServer((req, res) => {
if (req.url === '/health') { res.statusCode = 200; return res.end('ok'); }
res.end('Hello from the container');
});
server.listen(0, '127.0.0.1', () => console.log('PORT=' + server.address().port));
process.on('SIGTERM', () => server.close(() => { console.log('server stopped after SIGTERM'); }));
`);
// The health check used in HEALTHCHECK: exit 0 when healthy, 1 when not.
fs.writeFileSync(path.join(dir, 'healthcheck.js'), `
const http = require('node:http');
const req = http.get({ host: '127.0.0.1', port: process.env.PORT, path: '/health', timeout: 1000 }, (res) => {
process.exit(res.statusCode === 200 ? 0 : 1);
});
req.on('error', () => process.exit(1));
req.on('timeout', () => { req.destroy(); process.exit(1); });
`);
const check = (port) => spawnSync(process.execPath, [path.join(dir, 'healthcheck.js')], { env: { ...process.env, PORT: String(port) } }).status;
const server = spawn(process.execPath, [path.join(dir, 'server.js')], { stdio: ['ignore', 'pipe', 'inherit'] });
let output = '';
server.stdout.on('data', (chunk) => {
output += chunk;
const match = output.match(/PORT=(\d+)/);
if (!match || server.checked) return;
server.checked = true;
const port = match[1];
console.log('healthcheck while the server runs -> exit code', check(port));
server.kill('SIGTERM'); // what "docker stop" sends
});
server.on('exit', (code, signal) => {
console.log('server output:', output.split('\n').filter((l) => l && !l.startsWith('PORT')).join(' '));
console.log('server exit code:', code, '| killed by signal:', signal);
console.log('healthcheck after the server stopped -> exit code', check(server.checked ? output.match(/PORT=(\d+)/)[1] : 0));
fs.rmSync(dir, { recursive: true });
});
This snippet demonstrates the health check and the SIGTERM handling that the Dockerfile relies on. The Dockerfile text in the answer was not built here. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
healthcheck while the server runs -> exit code 0
server output: server stopped after SIGTERM
server exit code: 0 | killed by signal: null
healthcheck after the server stopped -> exit code 1
Key points
Pin versions, cache dependencies, npm ci --omit=dev.
Run as a non-root user with NODE_ENV=production.
Use exec form CMD ["node", ...] so signals arrive.
Handle SIGTERM in code. PID 1 has no default handler.
No secrets in the image.
Common mistakes
Starting the app with npm start inside the container and losing SIGTERM.
Copying the whole source before installing dependencies and losing the layer cache.
Running as root and baking .env into the image.
A health check that only tests that the process exists.
Follow-ups
What does docker run --init do?
How do you pass secrets to a container safely?
How would you keep the final image small?
Tips
Show the Dockerfile in the right order: dependencies first.
Explain PID 1 in one sentence.
Mention exec form versus shell form.
98.nodejs-0098Easyfresher
What does PM2 do for a Node.js app, and how do an ecosystem file, cluster mode and a graceful reload work?
PM2 is a process manager that starts Node apps, restarts them on a crash, keeps logs, and can run several copies in cluster mode. An ecosystem file describes the apps (script, instances, env, restart limits). pm2 reload restarts workers one by one for zero downtime, and the app can tell PM2 when it is ready with process.send('ready').
Full answer
A process manager keeps an app running after a crash, starts it on boot and gives basic monitoring. PM2 is the best-known one for Node. On container platforms the platform restarts crashed containers, so PM2 is mostly used on virtual machines and servers.
Common commands (not run on this box, PM2 is not installed here):
pm2 start ecosystem.config.js
pm2 list, pm2 logs, pm2 monit
pm2 restart app (stop and start), pm2 reload app (one by one, zero downtime in cluster mode)
pm2 save and pm2 startup: restart apps after a server reboot.
Ecosystem file (ecosystem.config.js) is a JavaScript module that exports { apps: [ ... ] }. Useful fields:
name, script, args, cwd.
instances: a number, or 'max' for one per CPU core. exec_mode: 'cluster' uses Node's cluster module so instances share the port.
env and env_production: environment variables, chosen with --env production.
max_memory_restart: restart a worker that grows past a limit ('300M'). A guard, not a fix for leaks.
wait_ready: true with listen_timeout: PM2 waits for process.send('ready') before it considers the app online and before it stops the old instance during a reload.
kill_timeout: how long PM2 waits after the stop signal (SIGINT by default) before it sends SIGKILL.
shutdown_with_message: use a message instead of a signal (useful on Windows).
Graceful reload recipe: the app starts its server, then calls process.send?.('ready'). On SIGINT it closes the server, finishes requests and exits, within kill_timeout. Then pm2 reload brings up new instances before the old ones leave.
Remember the cluster limits: no shared memory between instances, so keep state in an external store.
javascript
const { spawn } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
// 1. An ecosystem file is plain JavaScript. This is what you would save as ecosystem.config.js.
const ecosystem = {
apps: [{
name: 'schoolabe-api',
script: './server.js',
instances: 'max',
exec_mode: 'cluster',
wait_ready: true,
listen_timeout: 10000,
kill_timeout: 5000,
max_memory_restart: '300M',
env: { NODE_ENV: 'development', PORT: 3000 },
env_production: { NODE_ENV: 'production', PORT: 8080 },
}],
};
const app = ecosystem.apps[0];
console.log('app:', app.name, '| mode:', app.exec_mode, '| instances:', app.instances);
console.log('production env:', { ...app.env, ...app.env_production });
// 2. What PM2 expects from the app: tell "ready", and exit cleanly on SIGINT.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pm2-demo-'));
fs.writeFileSync(path.join(dir, 'server.js'), `
const http = require('node:http');
const server = http.createServer((req, res) => res.end('ok'));
server.listen(0, '127.0.0.1', () => {
if (process.send) process.send('ready'); // PM2 sets up this channel when wait_ready is on
});
process.on('SIGINT', () => {
server.close(() => { console.log('app: closed the server, exiting'); process.exit(0); });
});
`);
// The parent plays the role of PM2 for one reload step.
const child = spawn(process.execPath, [path.join(dir, 'server.js')], { stdio: ['ignore', 'pipe', 'inherit', 'ipc'] });
let output = '';
child.stdout.on('data', (chunk) => (output += chunk));
child.once('message', (message) => {
console.log('pm2 (simulated): app said', JSON.stringify(message), '-> mark it online, now stop the old instance');
child.kill('SIGINT'); // PM2 sends SIGINT to the old instance first
});
child.on('exit', (code) => {
console.log(output.trim());
console.log('exit code:', code);
fs.rmSync(dir, { recursive: true });
});
PM2 itself is not installed here, so the parent script plays PM2's part for one step. The pm2 commands in the answer were not run. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
app: schoolabe-api | mode: cluster | instances: max
production env: { NODE_ENV: 'production', PORT: 8080 }
pm2 (simulated): app said "ready" -> mark it online, now stop the old instance
app: closed the server, exiting
exit code: 0
Key points
PM2 restarts, scales and logs Node apps.
The ecosystem file describes apps, instances and env.
reload is zero downtime in cluster mode when the app signals ready.
Handle the stop signal (SIGINT by default) for a clean exit.
Common mistakes
Using restart instead of reload and dropping requests.
Running PM2 cluster mode and keeping sessions in memory.
Setting max_memory_restart and calling the leak solved.
Letting a crash loop run without min_uptime and max_restarts.
Follow-ups
How does PM2 cluster mode relate to the cluster module?
When would you not use PM2?
How does PM2 send logs and how do you rotate them?
Tips
Name restart versus reload.
Mention wait_ready and process.send('ready').
Say that containers often replace PM2.
99.nodejs-0099Easyfresher
What does NODE_ENV=production change, and why do dependencies and devDependencies matter for deployment?
Node itself ignores NODE_ENV. Frameworks and libraries read it to switch behaviour: Express caches views and hides stack traces, many libraries skip development checks and logging. npm install also skips devDependencies when NODE_ENV is production (or with --omit=dev), which keeps servers small. Set it on servers and keep staging and production the same, using a separate variable for the environment name.
Full answer
NODE_ENV is only a convention. The runtime does nothing with it, but a lot of code checks process.env.NODE_ENV.
What changes in production mode (library dependent):
Express: caches compiled views, produces less verbose error output (no stack traces in the default error handler), and uses other optimisations.
React, Vue and similar libraries: remove development warnings and checks, which makes them smaller and faster. Bundlers replace the variable at build time.
Logging and debugging helpers may reduce output.
Some libraries enable stricter security defaults or turn on caching.
Dependencies:
dependencies are installed always. devDependencies (tests, linters, build tools) are skipped by npm install --omit=dev, and by npm ci --omit=dev. Older npm used --production.
Put only what the app needs at run time in dependencies. A build tool in dependencies makes images larger and widens the attack surface.
Build steps that need dev tools happen before the omit step (multi-stage builds or a CI build job).
Advice:
Set NODE_ENV=production on every deployed environment, including staging, so staging behaves like production. Do not invent values such as 'staging' or 'qa' for NODE_ENV because libraries only know 'production' and 'development'. Use a separate variable (APP_ENV) for environment names.
Do not write your own logic that depends on many NODE_ENV values. Prefer explicit configuration flags.
Never ship code that works only when NODE_ENV is not set.
Test the app once with NODE_ENV=production locally, because some bugs appear only there.
javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
// A small Express app whose route throws an error. The default error handler decides what to show.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'node-env-'));
const expressPath = require.resolve('express');
fs.writeFileSync(path.join(dir, 'app.js'), `
const express = require(${JSON.stringify(expressPath)});
const app = express();
app.get('/crash', () => { throw new Error('database password is wrong'); });
const server = app.listen(0, '127.0.0.1', async () => {
const res = await fetch('http://127.0.0.1:' + server.address().port + '/crash');
const body = await res.text();
console.log('NODE_ENV =', process.env.NODE_ENV, '| status', res.status,
'| response shows the stack trace:', body.includes(' at '),
'| response shows the message:', body.includes('database password'));
server.close();
});
`);
for (const env of ['development', 'production']) {
const run = spawnSync(process.execPath, [path.join(dir, 'app.js')], { env: { ...process.env, NODE_ENV: env }, encoding: 'utf8' });
console.log(run.stdout.trim());
}
fs.rmSync(dir, { recursive: true });
The same route is served twice with a different NODE_ENV. In production the default error handler leaves out the stack trace and the error message. 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):
NODE_ENV = development | status 500 | response shows the stack trace: true | response shows the message: true
NODE_ENV = production | status 500 | response shows the stack trace: false | response shows the message: false
Key points
Node ignores NODE_ENV, libraries read it.
Express hides stack traces and caches views in production.
npm ci --omit=dev skips devDependencies.
Use APP_ENV for custom environment names.
Common mistakes
Setting NODE_ENV to custom names like staging.
Leaving build tools in dependencies.
Running production with NODE_ENV unset and getting slower, noisier behaviour.
Using NODE_ENV checks scattered in business code.
Follow-ups
What is the difference between npm install --omit=dev and npm ci --omit=dev?
How does a bundler use NODE_ENV?
How do you make the error handler safe in your own app?
Tips
Begin with 'Node itself ignores it'.
Give the Express example.
Say where custom environment names belong.
100.nodejs-0100Hardsenior
How do you scale a Node.js service, and how does load shedding protect it when traffic exceeds capacity?
Scale out by running many stateless copies behind a load balancer, move shared state to external stores, push slow work to queues, cache read-heavy data, and scale the database separately. When load exceeds capacity, shed it: cap in-flight requests or watch event loop delay, and answer 503 with Retry-After early, so accepted requests stay fast instead of every request becoming slow.
Full answer
Scaling patterns, in the order they usually pay off:
Profile first. Remove blocking code and slow queries before adding machines.
Vertical use of one machine: cluster mode, PM2 or several containers, one process per CPU core.
Horizontal scaling: stateless processes behind a load balancer. Sessions, caches and uploads live in Redis, a database or object storage. Sticky sessions are a fallback for WebSockets, not a goal.
Caching: HTTP caching and a CDN for public content, in-memory or Redis caches for hot data, with expiry and stampede protection.
Queues and background workers: accept the request quickly, put slow work (email, reports, image processing) on a queue, and process it with separate worker processes that scale on their own. Make jobs idempotent.
Database scaling: indexes, connection pooling with a limit, read replicas, partitioning. The database often fails before Node does.
Autoscaling on a good signal: CPU, event loop utilization, queue length or latency, with warm-up time in mind.
Protecting a service at the limit (admission control):
Without it, a spike makes the queue of requests grow. Every request waits, timeouts fire, clients retry, and the load grows further (a retry storm). The service collapses for everyone.
Load shedding rejects the excess quickly. Options: a limit on concurrent in-flight requests per process, rejecting when event loop delay or utilization is above a threshold, or when a queue is longer than N.
Reply 503 Service Unavailable with Retry-After. Clients with backoff then spread their retries.
Protect important paths: health checks and critical routes bypass shedding, and low priority work is shed first.
Add timeouts everywhere, and propagate deadlines, so work that nobody waits for is dropped.
Test with load tests above the expected peak, and watch the behaviour at 2x capacity.
The aim is graceful degradation: serve most users well, and refuse the rest clearly.
javascript
const http = require('node:http');
// Admission control: allow at most MAX_IN_FLIGHT requests at once, reject the rest quickly.
function withLoadShedding(handler, { maxInFlight, bypass = [] }) {
let inFlight = 0;
return (req, res) => {
if (bypass.includes(req.url)) return handler(req, res); // health checks always pass
if (inFlight >= maxInFlight) {
res.writeHead(503, { 'Retry-After': '1', 'Content-Type': 'application/json' });
return res.end(JSON.stringify({ error: 'server busy, retry later' }));
}
inFlight++;
res.on('close', () => { inFlight--; });
handler(req, res);
};
}
const slowHandler = (req, res) => {
if (req.url === '/health') return res.end('ok');
setTimeout(() => res.end('report ready'), 100); // a slow downstream call
};
const server = http.createServer(withLoadShedding(slowHandler, { maxInFlight: 2, bypass: ['/health'] }));
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
// Five clients arrive at the same moment.
const burst = await Promise.all(Array.from({ length: 5 }, async () => {
const response = await fetch(base + '/report', { headers: { Connection: 'close' } });
await response.text();
return { status: response.status, retryAfter: response.headers.get('retry-after') };
}));
console.log('served:', burst.filter((r) => r.status === 200).length);
console.log('shed with 503:', burst.filter((r) => r.status === 503).length, '| Retry-After header:', burst.find((r) => r.status === 503).retryAfter);
// The health check still works while the server is busy.
const busy = Array.from({ length: 2 }, () => fetch(base + '/report', { headers: { Connection: 'close' } }).then((r) => r.text()));
await new Promise((resolve) => setTimeout(resolve, 20));
const health = await fetch(base + '/health', { headers: { Connection: 'close' } });
console.log('health check while busy:', health.status);
await Promise.all(busy);
// After the burst, capacity is free again.
const again = await fetch(base + '/report', { headers: { Connection: 'close' } });
console.log('after the burst:', again.status);
server.close();
});
Two requests fit into the limit, three are refused at once, and the health check and the later request still work. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
served: 2
shed with 503: 3 | Retry-After header: 1
health check while busy: 200
after the burst: 200
Key points
Remove bottlenecks before adding machines.
Stateless copies, external state, queues and caches enable horizontal scaling.
The database is often the real limit.
Shed load early with 503 and Retry-After.
Protect health checks and critical routes.
Common mistakes
Adding servers before finding the real bottleneck.
Letting queues grow without a limit.
Retrying immediately without backoff and jitter.
Scaling Node instances while the database connection pool runs out.
Follow-ups
How would you choose the in-flight limit?
How do you shed load based on event loop delay?
How does a queue change the scaling picture?
Tips
Put the patterns in order of cost and benefit.
Explain the retry storm.
Say that 503 with Retry-After is a kind answer to a client.