Questions 61–80 of 200 · 0 of 20 on this page marked learned
61.nodejs-0061Easyfresher
What are the basics of Jest for testing Node.js code, and how does it differ from node:test?
Jest is a test framework with a test runner, expect matchers, mock functions (jest.fn, jest.spyOn), module mocking, fake timers, snapshots and coverage in one package. Tests use describe, test and expect. For Node services set testEnvironment to node. It needs a dependency, while node:test is built in.
Full answer
Jest is the most common JavaScript test framework. Typical file: sum.test.js.
Core API:
describe(name, fn) groups tests. test(name, fn) or it(name, fn) defines one.
expect(value) with matchers: toBe (Object.is), toEqual (deep, ignores undefined properties), toStrictEqual, toThrow, toContain, toMatchObject, resolves and rejects for promises.
jest.fn() creates a mock function with mock.calls and mock.results. jest.spyOn(object, 'method') watches or replaces a method and can be restored. jest.mock('./module') replaces a whole module. jest.useFakeTimers() controls time.
Snapshots: expect(value).toMatchSnapshot() compares with a stored file. Good for stable output, bad for large, noisy values.
Coverage: jest --coverage.
Configuration: in package.json under "jest", or jest.config.js. For back-end code use { "testEnvironment": "node" }. For ES modules, Jest needs extra setup (--experimental-vm-modules or a transform), which is one reason some teams choose Vitest or node:test.
Compared with node:test: Jest has a bigger feature set (snapshots, powerful module mocks, watch mode with filters) and many examples online, but it adds a large dependency and runs tests in a sandboxed VM context, which can hide real Node behaviour. node:test is smaller, faster to start, and uses real Node modules.
Run with npx jest, or npm test. Use --runInBand to run files serially when tests share a database.
The snippet creates a small project in a temporary folder and runs Jest on it with JSON output, so the result is easy to read. Install first with npm install jest (run here with jest 30.5.2). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
passed report average of three marks
passed report objects use toEqual
passed report publish sends one email
passed report spyOn watches an existing method
passed report errors are checked with toThrow
passed: 5 | failed: 0 | exit code: 0
Key points
describe, test and expect are the core.
jest.fn, spyOn and jest.mock are the mocking tools.
Set testEnvironment to node for server code.
Jest has more features. node:test has no extra dependency.
Common mistakes
Using toBe for objects and arrays, which compares references.
Forgetting await or return in an async test, so it passes too early.
Not restoring spies and mocks between tests.
Relying on snapshots for large, changing output.
Follow-ups
How does jest.mock differ from jest.spyOn?
How do you test ES modules with Jest?
What is the difference between toEqual and toStrictEqual?
Tips
Know toBe vs toEqual cold.
Say when you would pick node:test instead, to show judgement.
Mention that the node test environment is a setting you must choose.
62.nodejs-0062Easyfresher
How do you debug a Node.js program: console methods, the debugger statement, --inspect and the inspector module?
Start with console methods (log, table, dir, count, group, trace) for quick checks. For stepping through code, run node --inspect (or --inspect-brk to pause at the first line) and attach Chrome DevTools or VS Code, then use breakpoints, watches and the call stack. The node:inspector module speaks the same protocol from inside your program.
Full answer
Levels of debugging, from quick to thorough:
Console output. console.log is fine for small checks. Better tools: console.table(array) for rows, console.dir(obj, { depth: null }) for deep objects, console.count(label) for how often code runs, console.group for nesting, console.trace() for the call stack, console.error for stderr, and console.time/timeEnd for rough timings.
The debugger statement. When a debugger is attached, execution pauses at the line debugger;. Without a debugger it does nothing.
The inspector. node --inspect app.js opens a WebSocket (port 9229 by default) and prints a URL. Open chrome://inspect in Chrome and click inspect, or use the VS Code debugger (launch or attach). node --inspect-brk waits at the first line, which is needed for short scripts. You can set breakpoints, conditional breakpoints and logpoints, step over, into and out, watch expressions, inspect scopes and the async call stack, and take profiles and heap snapshots.
Environment helpers. NODE_DEBUG=http,net prints internal logs of core modules. The debug package uses DEBUG=app:* for your own namespaced logs.
The inspector module. new inspector.Session(), session.connect(), and session.post('Runtime.evaluate', ...) use the same protocol from code. It is the basis for taking profiles in a running process.
Security: never expose the inspector port to a network. Anyone who can connect can run any code. Bind to 127.0.0.1 (the default) and tunnel with SSH when debugging a remote process. Sending SIGUSR1 to a Node process also opens the inspector on a running process.
javascript
const inspector = require('node:inspector/promises');
const util = require('node:util');
// 1. Console helpers that write to standard output.
console.table([
{ student: 'Asha', marks: 78 },
{ student: 'Ravi', marks: 91 },
]);
console.group('Term 1');
console.log('maths: 78');
console.group('details');
console.log('graded by: Ms Rao');
console.groupEnd();
console.groupEnd();
console.count('login');
console.count('login');
console.dir({ a: { b: { c: { d: 1 } } } }, { depth: null });
console.log(util.inspect({ a: { b: { c: { d: 1 } } } }, { depth: 0 }));
// 2. The debugger statement does nothing without a debugger attached.
debugger;
// 3. Talk to the inspector from inside the program.
async function main() {
console.log('inspector url while closed:', inspector.url());
const session = new inspector.Session();
session.connect();
const { result } = await session.post('Runtime.evaluate', { expression: '6 * 7' });
console.log('Runtime.evaluate result:', result.type, result.value);
session.disconnect();
}
main();
console.error and console.trace write to stderr, so the snippet uses only the console methods that write to standard output. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
┌─────────┬─────────┬───────┐
│ (index) │ student │ marks │
├─────────┼─────────┼───────┤
│ 0 │ 'Asha' │ 78 │
│ 1 │ 'Ravi' │ 91 │
└─────────┴─────────┴───────┘
Term 1
maths: 78
details
graded by: Ms Rao
login: 1
login: 2
{
a: { b: { c: { d: 1 } } }
}
{ a: [Object] }
inspector url while closed: undefined
Runtime.evaluate result: number 42
Key points
console.table, dir, count, group and trace give fast insight.
--inspect plus DevTools or VS Code gives breakpoints and stepping.
--inspect-brk pauses on the first line.
The inspector port gives full code execution, so keep it local.
Common mistakes
Leaving console.log calls and debugger statements in production code.
Exposing --inspect=0.0.0.0 on a server.
Using --inspect for a short script and missing the breakpoint, instead of --inspect-brk.
Printing a large object with console.log and reading [Object] instead of using depth: null.
Follow-ups
How do you debug a process that is already running?
What are logpoints and why are they useful?
How do source maps help with TypeScript?
Tips
List the levels from console to inspector. It shows you pick the lightest tool.
Mention the security risk of the inspector port.
Know chrome://inspect by name.
63.nodejs-0063Hardsenior
How do you use heap snapshots to find what is leaking, step by step?
Take a snapshot after the app has warmed up, run the suspect workload, force garbage collection, take a second snapshot, and compare. The constructor whose instance count keeps growing is the suspect, and its retainer path shows which variable still holds it. In Node, v8.writeHeapSnapshot() writes a .heapsnapshot file that DevTools can open.
Full answer
A heap snapshot is a full list of live objects with their sizes and the references between them. It is the best tool for a growing heapUsed.
Method:
Warm up the app (load modules, fill normal caches) so start-up objects do not look like a leak.
Force a garbage collection (node --expose-gc and global.gc(), or the DevTools trash icon) and take snapshot 1.
Run a fixed amount of the suspect work, for example 1,000 requests.
Collect garbage again and take snapshot 2.
In Chrome DevTools, Memory tab, load both files, choose snapshot 2 and set the view to "Objects allocated between Snapshot 1 and Snapshot 2". Sort by count or retained size.
Open a suspicious constructor and read its Retainers panel from the bottom up. The path ends at a root such as a module variable, a closure, a Map, a timer or an event listener list. That is the reference you must remove.
Ways to take snapshots in Node: v8.writeHeapSnapshot(file), the --heapsnapshot-signal=SIGUSR2 flag (send the signal to a running process), the DevTools Memory tab over --inspect, or the heapdump-like APIs in diagnostics tools. A snapshot pauses the process and needs memory about twice the heap size, so take it on a staging copy or a single instance taken out of rotation.
Read the numbers carefully: shallow size is the object itself, retained size is what would be freed if the object went away. Growing counts of strings, arrays or closures usually point to a cache or listener list. The same analysis can be scripted by reading the JSON file, as the snippet shows.
javascript
const v8 = require('node:v8');
const vm = require('node:vm');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
v8.setFlagsFromString('--expose-gc');
const gc = vm.runInNewContext('gc');
class StudentSession {
constructor(id) { this.id = id; this.history = new Array(20).fill(id); }
}
const activeSessions = []; // the leak: sessions are added and never removed
function countInstances(className) {
gc();
const file = path.join(os.tmpdir(), `snap-${process.pid}-${Date.now()}.heapsnapshot`);
v8.writeHeapSnapshot(file);
const snapshot = JSON.parse(fs.readFileSync(file, 'utf8'));
fs.rmSync(file);
const fields = snapshot.snapshot.meta.node_fields;
const stride = fields.length;
const nameIndex = fields.indexOf('name');
const typeIndex = fields.indexOf('type');
const objectType = snapshot.snapshot.meta.node_types[0].indexOf('object');
let count = 0;
for (let i = 0; i < snapshot.nodes.length; i += stride) {
if (snapshot.nodes[i + typeIndex] === objectType && snapshot.strings[snapshot.nodes[i + nameIndex]] === className) count++;
}
return count;
}
const before = countInstances('StudentSession');
for (let i = 0; i < 500; i++) activeSessions.push(new StudentSession(i)); // 500 "requests"
const after = countInstances('StudentSession');
console.log('snapshot 1: StudentSession objects =', before);
console.log('snapshot 2: StudentSession objects =', after);
console.log('growth between snapshots:', after - before);
activeSessions.length = 0; // fix: release the references
console.log('after releasing the array, objects =', countInstances('StudentSession'));
The code reads the snapshot file the way DevTools does and counts objects by constructor name. Snapshot files are removed after reading. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
snapshot 1: StudentSession objects = 0
snapshot 2: StudentSession objects = 500
growth between snapshots: 500
after releasing the array, objects = 0
Key points
Compare two snapshots taken after garbage collection.
A growing instance count of one constructor is the lead.
The retainer path shows which reference keeps objects alive.
Snapshots pause the process and need a lot of memory.
Common mistakes
Taking a snapshot before warm-up and blaming start-up objects.
Comparing snapshots without forcing garbage collection first.
Taking a snapshot on a busy production instance.
Reading shallow size only and missing the large retained size.
Follow-ups
What is the difference between shallow size and retained size?
How would you find a leak in a process that runs in a container?
Which objects are GC roots?
Tips
Number the six steps. Interviewers want a method.
Say 'retainers' and explain that they answer who is holding the object.
Mention the cost of a snapshot to show care for production.
64.nodejs-0064Mediummid
How do you capture a CPU profile of a running Node.js program and find the hottest function?
Use node --cpu-prof to write a .cpuprofile file when the process exits, or start the profiler on demand through the inspector module (Profiler.start and Profiler.stop). Open the file in Chrome DevTools or VS Code to see a flame graph, and sort by self time to find the function that burns the CPU.
Full answer
A CPU profile samples the call stack about every millisecond. The more samples a function appears in, the more time it used.
Ways to get one:
node --cpu-prof app.js writes a file such as CPU.2026....cpuprofile when the process ends. Options: --cpu-prof-dir, --cpu-prof-interval.
node --inspect and the Performance or Profiler panel in DevTools, for a live process.
Code: inspector.Session, session.post('Profiler.enable'), 'Profiler.start', then 'Profiler.stop', which returns the profile object. This is how you build an endpoint that records 10 seconds of a staging process.
Tools built on the same data: 0x, clinic flame, and the VS Code profile viewer.
Reading a profile:
Self time: time inside the function body only.
Total time: self time plus callees.
A wide bar at the top of a flame graph is a hot function. Wide bars lower down are callers that spend time in children.
Look for JSON.parse and stringify, regular expressions, synchronous crypto, sorting, string concatenation in loops, and garbage collection ((garbage collector) entries).
(idle) and (program) entries are not your code. A mostly idle profile means the problem is waiting, not CPU.
Always profile with realistic load, with the same Node version and build, and compare before and after a change. A profile of an idle process is useless.
The profile format: nodes (call frames with ids), samples (a node id per sample) and timeDeltas (microseconds between samples). The snippet below aggregates self time by function name from that data.
javascript
const inspector = require('node:inspector/promises');
function checksumOfMarks(rounds) {
let total = 0;
for (let i = 0; i < rounds; i++) total += (i * 31) % 7;
return total;
}
function quickHelper() {
return Array.from({ length: 1000 }, (_, i) => i).length;
}
async function main() {
const session = new inspector.Session();
session.connect();
await session.post('Profiler.enable');
await session.post('Profiler.start');
checksumOfMarks(150_000_000); // the hot code
quickHelper();
const { profile } = await session.post('Profiler.stop');
session.disconnect();
// Add up self time (microseconds) per function name.
const byId = new Map(profile.nodes.map((node) => [node.id, node]));
const selfTime = {};
profile.samples.forEach((id, i) => {
const name = byId.get(id).callFrame.functionName || '(anonymous)';
selfTime[name] = (selfTime[name] || 0) + profile.timeDeltas[i];
});
const [hottest] = Object.entries(selfTime).sort((a, b) => b[1] - a[1])[0];
console.log('profile has samples:', profile.samples.length > 0);
console.log('hottest function by self time:', hottest);
console.log('quickHelper used less time than the hot function:', (selfTime.quickHelper || 0) < selfTime.checksumOfMarks);
}
main();
The profile data lists call frames and samples, so the script can find the hottest function without a UI. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
profile has samples: true
hottest function by self time: checksumOfMarks
quickHelper used less time than the hot function: true
Key points
Profiles sample call stacks, and self time shows hot functions.
--cpu-prof writes a file on exit. The inspector module records on demand.
(idle) means waiting, not CPU work.
Profile under realistic load and measure again after the fix.
Common mistakes
Profiling a process that is idle or has no load.
Reading total time as if it were self time.
Profiling a debug or different build and changing the wrong thing.
Optimising a function that uses 1 percent of the time.
Follow-ups
What is the difference between a CPU profile and a heap snapshot?
How do you profile code that runs in a worker thread?
What does a wide (garbage collector) bar mean?
Tips
Say 'self time versus total time' without being asked.
Name a way to capture a profile on demand, to show practical experience.
Describe the before and after comparison.
65.nodejs-0065Hardsenior
A Node.js service is slow. How do you decide whether the problem is CPU, the event loop, the thread pool or a slow dependency?
Check event loop utilization (ELU) and event loop delay first. High ELU with high delay means JavaScript is busy: profile the CPU. Low ELU with slow responses means the process is waiting: look at downstream calls, the thread pool, connection pools and locks. Growing memory points to heap snapshots, and high garbage collection time to allocation pressure.
Full answer
Do not guess. Use a short decision path that mirrors what tools such as clinic doctor report.
Step 1: measure.
Event loop utilization (performance.eventLoopUtilization()): the share of time the loop was running JavaScript instead of waiting. Near 1 means saturated.
Event loop delay (monitorEventLoopDelay): how late timers fire.
CPU usage of the process (process.cpuUsage(), or the host metric) and memory (process.memoryUsage()).
Latency percentiles per route from your metrics.
Step 2: classify.
High ELU, high delay, high CPU: JavaScript-bound. Take a CPU profile and fix the hot function, or move work to worker threads.
Low ELU, low CPU, high latency: waiting. The time is spent in a database, another service, a lock, a connection pool queue, or DNS. Add timing around outgoing calls and check pool sizes. Also check thread pool saturation (fs, crypto, dns.lookup tasks queueing).
High CPU but low ELU: work outside the main thread, such as garbage collection, the thread pool (hashing, compression) or worker threads. Check --trace-gc and the thread pool use.
Memory climbing: take heap snapshots. Frequent long GC pauses: reduce allocation or the retained set.
Latency spikes at regular intervals: look for timers, cron jobs, cache expiry or GC.
Step 3: change one thing, measure again with the same load (autocannon or k6).
The point is the order: cheap metrics first, a profiler second, and code changes last.
javascript
const { performance } = require('node:perf_hooks');
const { setTimeout: sleep } = require('node:timers/promises');
// Measure ELU over one piece of work and say what kind of problem it looks like.
async function diagnose(label, work) {
const start = performance.eventLoopUtilization();
await work();
const { utilization } = performance.eventLoopUtilization(start);
const verdict =
utilization > 0.8 ? 'JavaScript is busy: take a CPU profile'
: utilization < 0.2 ? 'mostly waiting: check dependencies, pools and the thread pool'
: 'mixed: measure per route';
console.log(label.padEnd(26), '->', verdict);
}
function busy(ms) {
const end = performance.now() + ms;
while (performance.now() < end) { /* spin */ }
}
async function main() {
await sleep(20); // let start-up settle
await diagnose('slow database call', () => sleep(300));
await diagnose('heavy calculation', async () => { await sleep(0); busy(300); });
await diagnose('half and half', async () => {
for (let i = 0; i < 5; i++) { busy(30); await sleep(30); }
});
}
main();
The three cases mimic a slow database call, a CPU-heavy handler and a mix. Real services should report ELU as a metric and alert on it. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
slow database call -> mostly waiting: check dependencies, pools and the thread pool
heavy calculation -> JavaScript is busy: take a CPU profile
half and half -> mixed: measure per route
Key points
ELU and event loop delay separate busy from waiting.
High ELU: profile the CPU. Low ELU with slow responses: look at dependencies and pools.
Guessing and optimising the code before measuring.
Treating high latency as a CPU problem when the loop is idle.
Looking at average CPU only and missing one saturated core.
Ignoring the thread pool when fs, dns or crypto calls queue.
Follow-ups
What does clinic doctor report, and how does it get its data?
How would you tell if the thread pool is the bottleneck?
What metric would you alert on for the event loop?
Tips
Give the decision path in order.
Name ELU as the first number you check.
Add that you change one thing at a time.
66.nodejs-0066Easyfresher
What is middleware, and how does a middleware chain with next() work?
Middleware is a function that receives the request, the response and a next function. It can read or change the request, end the response, or call next() to pass control to the following function. The chain runs in the order the functions were added, and code after next() runs again when the later steps are finished.
Full answer
Frameworks such as Express and Koa organise request handling as a list of small functions. Each function has one job: logging, parsing JSON, authentication, rate limiting, routing, or an error response.
Contract of a middleware (req, res, next):
Do some work with req and res.
Either end the response (res.end, res.json) or call next() to continue.
If you do neither, the request hangs.
If something fails, call next(err) (in Express) so that error handling middleware takes over.
Order matters. A body parser must come before the code that reads req.body. An authentication step must come before protected routes. A 404 handler comes after all routes, and error handlers come last.
The "onion" idea: code before next() runs on the way in. After next() returns (or its promise resolves, in Koa style) code runs on the way out. This is how a timing middleware measures the whole request.
Implementing the chain needs only a short function: keep an index, call the function at that index with a next that increments it. Express does exactly this, plus routing by method and path, and error middleware that has four parameters (err, req, res, next).
Using the pattern in your own code (command handlers, message consumers, API clients) is a clean way to add cross-cutting features without touching business code.
javascript
const http = require('node:http');
// A tiny middleware runner, similar in idea to Express.
function createApp() {
const stack = [];
const app = (req, res) => {
let index = 0;
const next = (err) => {
const fn = stack[index++];
if (!fn) {
res.statusCode = err ? 500 : 404;
return res.end(err ? 'Server error' : 'Not found');
}
try {
if (err && fn.length === 4) return fn(err, req, res, next); // error middleware
if (!err && fn.length < 4) return fn(req, res, next);
return next(err); // skip: wrong kind of function for this state
} catch (thrown) {
return next(thrown);
}
};
next();
};
app.use = (fn) => stack.push(fn);
return app;
}
const trace = [];
const app = createApp();
app.use((req, res, next) => { trace.push('timer: start'); res.on('finish', () => trace.push('timer: end')); next(); trace.push('timer: back after next'); });
app.use((req, res, next) => { trace.push('auth'); if (req.headers.authorization !== 'token-1') { res.statusCode = 401; return res.end('Unauthorized'); } next(); });
app.use((req, res, next) => { if (req.url === '/crash') throw new Error('bug'); next(); });
app.use((req, res) => { trace.push('handler'); res.end('Hello student'); });
app.use((err, req, res, next) => { trace.push('error handler: ' + err.message); res.statusCode = 500; res.end('Something went wrong'); });
const server = http.createServer(app);
server.listen(0, async () => {
const base = 'http://127.0.0.1:' + server.address().port;
const call = async (path, headers) => {
trace.length = 0;
const res = await fetch(base + path, { headers });
const body = await res.text();
await new Promise((r) => setImmediate(r));
console.log(path.padEnd(7), res.status, body.padEnd(22), '|', trace.join(' > '));
};
await call('/', { authorization: 'token-1' });
await call('/', {});
await call('/crash', { authorization: 'token-1' });
server.close();
});
Each request prints the status, body and the order in which the middleware ran, so the onion shape is visible. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
/ 200 Hello student | timer: start > auth > handler > timer: back after next > timer: end
/ 401 Unauthorized | timer: start > auth > timer: back after next > timer: end
/crash 500 Something went wrong | timer: start > auth > error handler: bug > timer: back after next > timer: end
Key points
Middleware has the shape (req, res, next).
Call next() to continue, or end the response.
Order is behaviour. Add functions in the right order.
Code after next() runs on the way out, like an onion.
Common mistakes
Forgetting to call next(), so the request hangs.
Calling next() after already sending the response, which causes errors.
Registering the 404 handler before the routes.
Putting the body parser after the route that needs it.
Follow-ups
How does Koa's await next() differ from Express next()?
Why do error handlers have four parameters in Express?
How would you apply middleware only to some routes?
Tips
Draw the onion and mark in and out.
State the three outcomes of a middleware: respond, next, error.
Mention that order is part of the behaviour.
67.nodejs-0067Mediummid
How does a request move through an Express application, and how do error handling and async errors work in Express 5?
A request goes through app-level middleware in the order registered, then the matching route handlers, and ends at a response, the 404 handler or the error handler. In Express 5, a rejected promise or thrown error in an async handler is forwarded to the error middleware automatically, which Express 4 did not do.
Full answer
The Express request lifecycle:
The server gets the request and Express creates req and res (extended Node objects).
app.use middleware runs in registration order: logging, security headers, body parsing (express.json()), authentication.
Routing: app.get('/path', ...handlers) matches method and path. A route can have several handlers and calls next() to move to the next one. next('route') skips the rest of this route.
A handler sends a response (res.json, res.send, res.status(...).end). After the response is sent, the rest of the chain should not write again.
If nothing responded, the request reaches the final "not found" middleware you add after all routes.
If any step throws or calls next(err), Express skips normal middleware and runs error handlers: functions with four parameters (err, req, res, next), registered after the routes.
Express 5 change: handlers that return a rejected promise (or async functions that throw) pass the error to next(err) on their own. In Express 4 you needed try/catch plus next(err), or a wrapper library. Synchronous throws were caught in both versions.
Good practice for errors:
Create one error handler that maps known errors to status codes and a safe message, and logs the rest.
Never send err.stack to clients in production.
If headers are already sent, call next(err) and let Express close the connection.
Place the 404 handler before the error handler, and both after all routes.
Useful extras: res.on('finish') to run code after the response is flushed, app.set('trust proxy') behind a proxy, and router objects (express.Router) to group routes.
javascript
const express = require('express');
const app = express();
let trace = [];
app.use((req, res, next) => {
trace.push('logger in');
res.on('finish', () => trace.push('finished ' + res.statusCode));
next();
trace.push('logger out');
});
app.get('/students',
(req, res, next) => { trace.push('route step 1'); next(); },
(req, res) => { trace.push('route step 2'); res.json([{ id: 1 }]); });
app.get('/async-fail', async () => { // no try/catch, no next(err)
await Promise.resolve();
throw new Error('database unavailable');
});
app.use((req, res) => res.status(404).json({ error: 'not found' })); // after all routes
app.use((err, req, res, next) => { // four parameters: error handler
trace.push('error handler');
res.status(500).json({ error: 'internal error' }); // no stack trace for the client
});
const server = app.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
for (const path of ['/students', '/async-fail', '/missing']) {
trace = [];
const res = await fetch(base + path);
await res.text();
await new Promise((r) => setImmediate(r));
console.log(path.padEnd(12), res.status, '|', trace.join(' > '));
}
server.close();
});
The async handler throws without any try/catch, and Express 5 still sends the error to the error middleware. 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):
/students 200 | logger in > route step 1 > route step 2 > logger out > finished 200
/async-fail 500 | logger in > logger out > error handler > finished 500
/missing 404 | logger in > logger out > finished 404
Key points
Order of registration decides order of execution.
Error middleware has four parameters and comes last.
Express 5 forwards async errors automatically.
404 handler goes after routes, before the error handler.
Common mistakes
Writing the error handler before the routes.
Giving the error handler three parameters, so Express treats it as normal middleware.
Sending a response and then calling next().
Sending err.message or err.stack of unknown errors to clients.
Follow-ups
How did you handle async errors in Express 4?
What does next('route') do?
How do you add a request timeout in Express?
Tips
Narrate the lifecycle in six steps.
Know the Express 5 async change by name.
Say the error handler is the last middleware.
68.nodejs-0068Mediummid
What is the Fastify request lifecycle, and how do hooks and JSON schema validation work?
Fastify runs a fixed order of hooks for each request: onRequest, preParsing, preValidation, preHandler, the handler, preSerialization, onSend and onResponse. Routes can declare JSON schemas for body, query, params and response. Fastify validates input with the schema (400 on failure) and uses the response schema to serialize quickly.
Full answer
Fastify is a web framework focused on speed and structure. Its request lifecycle is explicit:
Routing finds the route.
onRequest hook: first chance to look at the request (authentication, request ids).
preParsing: access to the raw payload stream before parsing.
Body parsing by content type (JSON by default).
preValidation: before the schema check.
Validation: the route schema checks body, querystring, params and headers. A failure answers 400 with a message.
preHandler: authorization, loading data that the handler needs.
The handler. It can return a value (or a promise) or use reply.send().
preSerialization: change the payload before it is turned into JSON.
onSend: change the final string or buffer, set headers.
onResponse: after the response is sent, good for metrics.
onError and onTimeout fire in failure cases.
Hooks can be async functions. Throwing an error, or sending a reply, in a hook ends the chain.
Schemas: Fastify compiles JSON Schema with Ajv for validation and with fast-json-stringify for output. A response schema both speeds up serialization and acts as a filter: properties not in the schema (such as a password hash) are dropped.
Testing is easy with fastify.inject(), which simulates a request without opening a port, returning statusCode, headers and body.
Compared with Express: Fastify is schema-first, has encapsulated plugins, and handles async handlers from the start. Express is smaller to learn and has more third-party middleware.
The response schema removes internalNote, and the invalid request never reaches the handler. Install first with npm install fastify (run here with fastify 5.12.8). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
valid request: 201 {"id":1,"name":"Asha"}
hook order: onRequest > preParsing > preValidation > preHandler > handler > preSerialization > onSend > onResponse
invalid request: 400 | body/marks must be <= 100
Key points
Hooks run in a fixed order for every request.
Schemas validate input and speed up and filter output.
A hook that sends a reply ends the chain.
inject() tests routes without a socket.
Common mistakes
Putting authentication in preHandler when it should be earlier in onRequest.
Using res or Express-style middleware signatures in Fastify hooks.
Skipping response schemas and missing the speed and filtering benefits.
Calling reply.send and also returning a value in an async handler.
Follow-ups
How is Fastify validation different from validating inside the handler?
How do you add a custom error handler?
What does fastify.inject return?
Tips
List the hooks in order from memory, or at least the main five.
Say that response schemas can protect against data leaks.
Mention inject for fast tests.
69.nodejs-0069Hardsenior
How do Fastify plugins and encapsulation work, and when do you use fastify-plugin?
Every plugin registered with app.register runs in its own encapsulated context. Decorators, hooks and routes added inside it are visible to that plugin and its children, but not to parents or siblings. Wrapping a plugin with fastify-plugin removes that boundary, so shared things such as a database client become available to the whole app.
Full answer
In Fastify, an application is a tree of plugins. app.register(plugin, options) creates a child context. Each context inherits from its parent:
Decorators (app.decorate('db', ...), request.decorate, reply.decorate) added in a child are not visible outside it.
Hooks added in a child apply only to routes inside that context and its children.
Routes registered in a context get the prefix option of that register call (for example /api/v1).
Why this design? It keeps modules isolated. A plugin for admin routes can add an authentication hook that does not touch public routes. Two plugins cannot clash over a decorator name. It also makes the load order explicit: Fastify loads plugins with avvio, and await app.ready() waits for all of them.
When you want to share something with the parent (a database connection, a configuration object, a metrics hook for every route), the plugin must break encapsulation. fastify-plugin does that: fp(async function (app) { ... }) sets the skip-override marker, so the plugin runs in the parent's context. It can also declare a name, dependencies and a version range for Fastify.
Guidelines:
Wrap shared infrastructure plugins in fp. Keep route plugins unwrapped.
Use options to pass configuration. Do not read globals inside plugins.
Close resources with the onClose hook, so app.close() shuts everything down.
Split by feature (students, courses), not by technical layer.
A common mistake is registering a database plugin without fp and then finding that app.db is undefined in sibling plugins.
javascript
const Fastify = require('fastify');
const fp = require('fastify-plugin');
async function main() {
const app = Fastify();
// Plugin 1: encapsulated. Its decorator stays inside.
app.register(async function privatePlugin(instance) {
instance.decorate('secret', 'only visible inside');
instance.addHook('onRequest', async (request, reply) => { reply.header('x-from-private-plugin', 'yes'); });
instance.get('/inside', async () => ({ secret: instance.secret }));
});
// Plugin 2: wrapped with fastify-plugin, so the decorator is shared with the parent.
app.register(fp(async function sharedPlugin(instance) {
instance.decorate('db', { find: (id) => ({ id, name: 'Asha' }) });
}, { name: 'shared-db' }));
// A route in the root context.
app.get('/outside', async () => ({
seesSecret: typeof app.secret,
seesDb: typeof app.db,
student: app.db.find(1),
}));
// A prefixed route group that uses the shared decorator.
app.register(async function api(instance) {
instance.get('/student/:id', async (request) => instance.db.find(Number(request.params.id)));
}, { prefix: '/api/v1' });
await app.ready();
for (const url of ['/inside', '/outside', '/api/v1/student/7']) {
const res = await app.inject(url);
console.log(url.padEnd(18), res.statusCode, res.body, '| private hook header:', res.headers['x-from-private-plugin'] || 'none');
}
await app.close();
}
main();
The private hook only adds its header to routes inside its own plugin. Install first with npm install fastify fastify-plugin (run here with fastify 5.12.8, fastify-plugin 6.0.1). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
/inside 200 {"secret":"only visible inside"} | private hook header: yes
/outside 200 {"seesSecret":"undefined","seesDb":"object","student":{"id":1,"name":"Asha"}} | private hook header: none
/api/v1/student/7 200 {"id":7,"name":"Asha"} | private hook header: none
Key points
register creates an encapsulated child context.
Decorators and hooks stay inside their context.
fastify-plugin shares a plugin with the parent context.
Use onClose to release resources.
Common mistakes
Registering a database plugin without fastify-plugin and then not finding the decorator.
Wrapping every plugin in fp and losing the isolation.
Using a hook on the root app when it should apply to one group of routes.
Forgetting await app.ready() before using decorated values.
Follow-ups
How does Fastify decide the load order of plugins?
How do you test one plugin in isolation?
When would you choose encapsulation over a shared hook?
Tips
Describe the tree of contexts in one sentence.
Say when you reach for fp: shared infrastructure.
Mention onClose for clean shutdown.
70.nodejs-0070Hardsenior
Write Express middleware for a request id and a token bucket rate limiter. What matters in the design?
A request id middleware reuses an incoming id or creates one, stores it on the request and sets it on the response so logs can be linked. A token bucket rate limiter keeps a bucket of tokens per client that refills over time. Each request takes one token. With no tokens, answer 429 with a Retry-After header. Inject the clock so the logic is testable.
Full answer
Request id middleware:
Accept an id from a trusted header (x-request-id) or create one with crypto.randomUUID().
Put it on req (req.id) and on the response header, and include it in every log line and error response.
Validate or limit the length of incoming ids, because they end up in logs.
Token bucket rate limiter:
Each client (IP address, API key or user id) has a bucket with capacity C tokens and a refill rate R tokens per second.
On a request, add the tokens earned since the last request (elapsed seconds times R, up to C), then remove one. If there is none, reject.
Compared with a fixed window counter, a token bucket allows short bursts up to C but keeps the long-term average at R, and it has no boundary effect at the window edge.
Answer 429 Too Many Requests and send Retry-After in seconds. Also useful: RateLimit-Limit and RateLimit-Remaining style headers.
Design points:
Key choice matters. Behind a proxy, req.ip needs app.set('trust proxy', ...) or every client looks the same.
Memory: remove idle buckets (a periodic sweep or an LRU), or the map grows without end.
Several servers need a shared store such as Redis with an atomic script. An in-memory limiter limits each process separately.
Inject the clock (a now function) so tests do not wait.
Put the limiter early in the chain, after the request id, so rejected requests are still logged with an id.
For production use a tested library, but know how it works.
The clock is a plain variable, so a second passes without any waiting. The custom request id is accepted because it matches the allowed pattern. 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):
request 1 200 | retry-after: - | id echoed: true
request 2 200 | retry-after: - | id echoed: true
request 3 (custom id) 200 | retry-after: - | id echoed: true
request 4 (bucket empty) 429 | retry-after: 1 | id echoed: true
request 5 after 1 second 200 | retry-after: - | id echoed: true
request 6 (empty again) 429 | retry-after: 1 | id echoed: true
Key points
Request ids connect logs, responses and errors.
Token bucket: capacity allows bursts, refill rate sets the average.
Return 429 with Retry-After.
Choose the key carefully and clean up idle buckets.
A multi-server setup needs a shared store.
Common mistakes
Using req.ip behind a proxy without trust proxy, so all users share one bucket.
Never removing old buckets.
Counting rejected requests as spent tokens.
Running the limiter per process and expecting a global limit.
Follow-ups
How does a sliding window limiter differ from a token bucket?
How would you implement this limiter in Redis?
How would you give different limits to different API keys?
Tips
Explain burst versus average in one line.
Mention Retry-After and the clock injection.
State the multi-server limitation.
71.nodejs-0071Easyfresher
How do you read configuration from environment variables in Node.js, and what do --env-file, process.loadEnvFile and util.parseEnv do?
process.env holds environment variables as strings. Node 20.6 and later can load a .env file with the --env-file flag, process.loadEnvFile() loads one from code, and util.parseEnv() parses the text without changing process.env. Variables that are already set in the real environment win over values in the file.
Full answer
Configuration that changes between environments (ports, database URLs, API keys) should not be written in code. Environment variables are the simplest way to supply it.
Facts about process.env:
Every value is a string, or undefined when missing. Convert numbers and booleans yourself: Number(process.env.PORT). The text 'false' is a truthy string.
Setting process.env.X = 5 stores the string '5'.
Changes affect only the current process and its children.
.env files:
A .env file has KEY=value lines, with comments starting with # and optional quotes. It is for local development. Never commit it. Commit a .env.example with fake values.
node --env-file=.env app.js loads it before your code starts. Use --env-file-if-exists for an optional file (Node 22 and later), and repeat the flag for several files, where later files override earlier ones.
process.loadEnvFile(path) loads a file from code (Node 21.7 and 20.12 and later).
util.parseEnv(text) returns an object and does not touch process.env. It is useful in tests.
Before these features most projects used the dotenv package, which is still common.
Production: set variables in the platform (container environment, Kubernetes secrets, a secret manager), not in files inside the image.
NODE_ENV: a convention. Libraries such as Express change behaviour when it equals 'production' (for example caching views, less verbose errors). Node itself ignores it. Set it to 'production' on servers, and do not invent many values such as 'staging' that libraries do not know; use a separate variable for that.
javascript
const { parseEnv } = require('node:util');
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const text = `
# local settings
PORT=3000
APP_NAME="Schoolabe API"
DEBUG=false
EMPTY=
`;
// 1. parseEnv only parses. It does not change process.env.
const parsed = parseEnv(text);
console.log('parsed:', parsed);
console.log('process.env.PORT is set by parseEnv:', process.env.PORT !== undefined);
// 2. Values are strings: the usual traps.
console.log('typeof PORT:', typeof parsed.PORT, '| PORT + 1 =', parsed.PORT + 1, '| Number(PORT) + 1 =', Number(parsed.PORT) + 1);
console.log('"false" is truthy:', Boolean(parsed.DEBUG));
// 3. loadEnvFile and --env-file in a child process.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'env-'));
const file = path.join(dir, '.env');
fs.writeFileSync(file, text);
const viaFlag = spawnSync(process.execPath, ['--env-file=' + file, '-p', 'process.env.APP_NAME'], { encoding: 'utf8' });
console.log('--env-file:', viaFlag.stdout.trim());
const viaCode = spawnSync(process.execPath, ['-e', `process.loadEnvFile(${JSON.stringify(file)}); console.log(process.env.PORT)`], { encoding: 'utf8' });
console.log('process.loadEnvFile:', viaCode.stdout.trim());
// 4. A value that is already in the environment wins over the file.
const override = spawnSync(process.execPath, ['--env-file=' + file, '-p', 'process.env.PORT'], {
encoding: 'utf8',
env: { ...process.env, PORT: '8080' },
});
console.log('real environment wins over the file:', override.stdout.trim());
fs.rmSync(dir, { recursive: true });
The child processes show how the flag and loadEnvFile behave, without changing the environment of this script. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
parsed: { APP_NAME: 'Schoolabe API', DEBUG: 'false', EMPTY: '', PORT: '3000' }
process.env.PORT is set by parseEnv: false
typeof PORT: string | PORT + 1 = 30001 | Number(PORT) + 1 = 3001
"false" is truthy: true
--env-file: Schoolabe API
process.loadEnvFile: 3000
real environment wins over the file: 8080
Key points
process.env values are always strings.
--env-file, loadEnvFile and parseEnv are built in.
Never commit .env. Commit .env.example.
Production values come from the platform.
Common mistakes
Committing a .env file with real secrets.
Using if (process.env.FLAG) when the value is the string 'false'.
Assuming process.env.PORT is a number.
Reading process.env all over the code instead of in one config module.
Follow-ups
Why read the environment in one place only?
How do you handle secrets in Kubernetes?
What does NODE_ENV change in Express?
Tips
Mention that all values are strings in the first sentence.
Know the flag --env-file and the function util.parseEnv.
Say .env is for development, the platform is for production.
72.nodejs-0072Mediummid
What do the twelve-factor rules mean for a Node.js service, and how do you load configuration that fails fast?
The twelve-factor method describes apps that are easy to deploy and scale: config in the environment, stateless processes, logs as a stream to stdout, fast start and graceful stop, backing services as attached resources, and the same code in every environment. A config module should read the environment once, validate every value, and stop the process with a clear message when something is wrong.
Full answer
Factors that matter most for Node services:
Codebase: one repository per app, many deploys from it.
Dependencies: declare everything in package.json and the lock file. Do not rely on global installs.
Config: store in environment variables, strictly separate from code. If the repository were public tomorrow, no secret should leak.
Backing services: databases, queues and caches are attached through URLs in config. Replacing a local database with a managed one needs no code change.
Build, release, run: build once (npm ci, compile), combine with config into a release, run it. Do not change code on a server.
Processes: stateless. Keep sessions and uploads in a database or object storage. This lets you run N copies.
Port binding: the app listens on a port from PORT. It does not rely on an external web server.
Concurrency: scale by adding processes, not by making one huge process.
Disposability: fast start-up, graceful shutdown on SIGTERM, jobs that survive a crash.
Dev and prod parity: same services and similar versions in development and production (containers help).
Logs: write to stdout as a stream of events. The platform collects them.
Admin processes: one-off tasks (migrations) run as separate commands in the same release.
Config loading rules:
Read process.env in one module only.
Convert types (numbers, booleans, lists) and apply defaults for non-secret values.
Validate all values and report all problems in one message, not just the first one.
Exit with a non-zero code at start-up when config is invalid. A service that boots with a bad config and fails later is much harder to diagnose.
Freeze the result and never log secret values.
javascript
function loadConfig(env) {
const errors = [];
const text = (name, { required = true, secret = false, fallback } = {}) => {
const value = env[name] ?? fallback;
if (value === undefined || value === '') {
if (required) errors.push(`${name} is required`);
return undefined;
}
return value;
};
const integer = (name, { min = 0, max = 65535, fallback } = {}) => {
const raw = env[name] ?? fallback;
const value = Number(raw);
if (raw === undefined || !Number.isInteger(value) || value < min || value > max) {
errors.push(`${name} must be an integer from ${min} to ${max}, got ${JSON.stringify(raw)}`);
return undefined;
}
return value;
};
const flag = (name, fallback = 'false') => {
const raw = (env[name] ?? fallback).toLowerCase();
if (!['true', 'false', '1', '0'].includes(raw)) {
errors.push(`${name} must be true or false, got ${JSON.stringify(env[name])}`);
return undefined;
}
return raw === 'true' || raw === '1';
};
const config = {
port: integer('PORT', { fallback: '3000' }),
databaseUrl: text('DATABASE_URL'),
jwtSecret: text('JWT_SECRET', { secret: true }),
debug: flag('DEBUG'),
logLevel: text('LOG_LEVEL', { required: false, fallback: 'info' }),
};
if (errors.length > 0) {
const error = new Error('Invalid configuration:\n - ' + errors.join('\n - '));
error.code = 'INVALID_CONFIG';
throw error;
}
return Object.freeze(config);
}
function describe(config) {
// Never print secrets.
return { ...config, jwtSecret: config.jwtSecret ? '[hidden]' : undefined };
}
// A good environment
const good = loadConfig({ PORT: '8080', DATABASE_URL: 'postgres://db/schoolabe', JWT_SECRET: 'long-random-value', DEBUG: 'false' });
console.log('valid config:', describe(good));
console.log('config is frozen:', Object.isFrozen(good));
// A bad environment: all problems are reported together.
try {
loadConfig({ PORT: 'eighty', DEBUG: 'maybe' });
} catch (err) {
console.log(err.code);
console.log(err.message);
// In a real service: console.error(err.message); process.exit(1);
}
The second call fails on purpose (error on purpose). A real service would print the message and exit with code 1 before it starts listening. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
valid config: {
port: 8080,
databaseUrl: 'postgres://db/schoolabe',
jwtSecret: '[hidden]',
debug: false,
logLevel: 'info'
}
config is frozen: true
INVALID_CONFIG
Invalid configuration:
- PORT must be an integer from 0 to 65535, got "eighty"
- DATABASE_URL is required
- JWT_SECRET is required
- DEBUG must be true or false, got "maybe"
Key points
Config in the environment, processes stateless, logs to stdout.
One module reads and validates process.env.
Report all config errors together and exit at start-up.
Disposability means fast start and graceful stop.
Common mistakes
Reading process.env in many files.
Treating the string 'false' as false.
Starting the server with a missing setting and failing on the first request.
Logging the whole config object, including secrets.
Follow-ups
Which twelve-factor rule is hardest to follow with WebSockets?
How do feature flags relate to config?
How would you run database migrations as an admin process?
Tips
Pick four or five factors and give a Node example for each.
Say 'fail fast at start-up' and show validation.
Mention that secrets never reach the logs.
73.nodejs-0073Hardsenior
How do you build layered configuration (defaults, file, environment, command line) with util.parseArgs, and keep secrets out of the logs?
Merge sources in a fixed order of precedence, usually defaults, then a config file, then environment variables, then command-line flags. util.parseArgs parses flags without a dependency. Record where each value came from for debugging, deep-freeze the result, and redact secret keys whenever the config is printed.
Full answer
Real services get settings from several places. A clear order avoids surprises. A common order, from lowest to highest priority:
Built-in defaults in code (safe values for development).
A config file (config.json or YAML) for non-secret structured settings.
Environment variables (deployment settings and secrets).
Command-line flags (one-off overrides, such as --port 4000).
Implementation points:
util.parseArgs({ args, options: { port: { type: 'string', short: 'p' }, verbose: { type: 'boolean' } }, strict: true }) returns { values, positionals }. In strict mode, unknown flags throw, which catches typos. It supports short flags, string and boolean types, multiple values and defaults.
Map each environment variable to a config key in a table (APP_PORT to port). A mapping table is easier to review than scattered process.env reads.
Convert and validate types after merging, not before.
Keep the source of every value ('default', 'file', 'env', 'cli'). When a value is wrong, the message says where it came from.
Deep-freeze the final object so code cannot change it at run time.
Redact secrets in output: a list of key names (password, token, secret, key) replaced by '[redacted]'. Do it in one function that all logging of config uses.
Never put secrets in command-line flags: process listings and shell history show them. Prefer environment variables, mounted secret files or a secret manager.
Reload on change is optional and risky. Many services restart on a config change instead, which keeps the state simple.
The sources are simulated with plain objects so the output is the same everywhere. The misspelled flag at the end fails on purpose. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
final config (secrets hidden): {
port: 8080,
logLevel: 'debug',
dbPassword: '[redacted]',
verbose: true,
files: [ 'extra-file.txt' ]
}
where each value came from: { port: 'env', logLevel: 'cli', dbPassword: 'env', verbose: 'cli' }
config is frozen: true
unknown flag rejected: ERR_PARSE_ARGS_UNKNOWN_OPTION
Applying precedence inconsistently in different parts of the app.
Printing the config for debugging with secrets inside.
Allowing unknown flags silently, so typos pass.
Follow-ups
How would you hot-reload config safely?
How do you manage secrets in Kubernetes?
How do CLI libraries like commander compare to parseArgs?
Tips
State the precedence order first.
Mention provenance (source tracking) as a debugging aid.
Say why secrets do not belong in argv.
74.nodejs-0074Mediummid
Why use structured (JSON) logging, and how do log levels, child loggers and redaction work in Pino?
Structured logs are one JSON object per line with fields such as level, time, message and request id, so tools can search and aggregate them. Pino writes them fast to stdout. Levels filter noise, child loggers add fixed fields (like requestId) to every line, and redact paths hide secrets.
Full answer
Text logs ("User 42 logged in from 10.0.0.5") are easy to read but hard to query. A JSON line such as {"level":30,"msg":"login","userId":42,"ip":"10.0.0.5"} can be filtered by any field, counted, graphed and alerted on in tools like Loki, Elasticsearch or CloudWatch.
Pino is a popular logger for Node because it is fast: it does little work in the main thread and writes newline-delimited JSON to stdout (or a destination stream).
Main ideas:
Levels: trace (10), debug (20), info (30), warn (40), error (50), fatal (60). The level option sets the minimum. In production use info, and switch to debug for a short time when investigating.
Message and fields: logger.info({ userId: 42 }, 'login ok'). Put data in fields, not in the message text, so each message stays constant and is easy to group.
Child loggers: const log = logger.child({ requestId }) adds fixed bindings to every line from log. Create one per request.
Redaction: redact: ['req.headers.authorization', 'password'] replaces values with [Redacted] (or removes them). This protects secrets that end up in logged objects.
Errors: log errors as err: logger.error({ err }, 'payment failed'). Pino has serializers that include type, message and stack.
Pretty printing (pino-pretty) is for development only. In production keep raw JSON and let the platform collect it.
General rules: log events, not noise; one line per event; no secrets or personal data; include ids that let you follow a request across services.
javascript
const pino = require('pino');
const { Writable } = require('node:stream');
// Collect the log lines so the example can print them.
const lines = [];
const sink = new Writable({
write(chunk, encoding, callback) {
lines.push(chunk.toString().trim());
callback();
},
});
const logger = pino(
{
level: 'info',
base: null, // no pid and hostname in this demo
timestamp: false, // no time, so the output is stable
redact: ['password', 'headers.authorization'],
formatters: { level: (label) => ({ level: label }) }, // "info" instead of 30
},
sink,
);
logger.debug('this line is below the info level and is dropped');
logger.info({ userId: 42 }, 'login ok');
// One child logger per request adds the same field to every line.
const requestLog = logger.child({ requestId: 'req-7' });
requestLog.info({ route: '/marks', ms: 12 }, 'request finished');
requestLog.warn({ password: 'secret123', headers: { authorization: 'Bearer abc', accept: 'json' } }, 'bad payload');
requestLog.error({ err: new RangeError('marks out of range') }, 'validation failed');
for (const line of lines) {
const entry = JSON.parse(line);
if (entry.err) entry.err = { type: entry.err.type, message: entry.err.message }; // hide the stack for a short output
console.log(JSON.stringify(entry));
}
The debug line is dropped by the level setting. The password and the authorization header are replaced by [Redacted]. Install first with npm install pino (run here with pino 10.4.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
{"level":"info","userId":42,"msg":"login ok"}
{"level":"info","requestId":"req-7","route":"/marks","ms":12,"msg":"request finished"}
{"level":"warn","requestId":"req-7","password":"[Redacted]","headers":{"authorization":"[Redacted]","accept":"json"},"msg":"bad payload"}
{"level":"error","requestId":"req-7","err":{"type":"RangeError","message":"marks out of range"},"msg":"validation failed"}
Key points
One JSON object per line makes logs searchable.
Levels set how much is written.
Child loggers add context such as requestId.
Redaction hides secrets.
Pretty printing is for development only.
Common mistakes
Putting variable data into the message text so lines cannot be grouped.
Logging full request bodies, tokens or personal data.
Using pino-pretty in production.
Creating a new logger per call instead of using child loggers.
Follow-ups
How does Pino stay fast?
How would you change the log level without a restart?
How do you correlate logs across microservices?
Tips
Show a JSON line and say what a query on it could do.
Name the six levels.
Mention redaction as a security feature.
75.nodejs-0075Easyfresher
What is the difference between console.log, console.error, process.stdout and process.stderr, and can output be lost when a process exits?
console.log writes to standard output (stdout) and console.error writes to standard error (stderr). They are separate streams, so they can be redirected independently. Writes to pipes are asynchronous on some platforms, so calling process.exit() right after a large write can cut output. Set process.exitCode and let the process end naturally.
Full answer
Every process has three standard streams: stdin (input), stdout (normal output) and stderr (errors and diagnostics). In a terminal both outputs show on the screen, but in scripts and containers they are separate: node app.js > out.txt 2> err.txt sends them to different files.
console.log, console.info and console.table write to process.stdout. console.error, console.warn and console.trace write to process.stderr.
process.stdout.write(text) is the lower-level call. It does not add a newline, and returns false when the internal buffer is full (backpressure).
Format: console.log uses util.format, so %s, %d, %j and %o placeholders work.
Synchronous or not: files and TTYs are written synchronously. Pipes and sockets are synchronous on Linux, but asynchronous on Windows pipes in some cases (check the Node docs for the current rules). So process.exit() right after logging a lot can lose data when the output goes through an asynchronous pipe, for example a parent process reading your output.
Good habits:
Prefer process.exitCode = 1 and let the event loop empty, instead of process.exit(1).
In long-running services write logs to stdout and let the platform collect them (twelve-factor).
Send errors and diagnostics to stderr, data results to stdout, so command-line tools can be piped: node report.js | sort.
Use process.stdout.isTTY to detect a terminal, for example to disable colors when output is piped.
Do not log inside tight loops. Console output is slow compared with memory work.
javascript
const { spawnSync } = require('node:child_process');
const childCode = `
console.log('result: 42'); // stdout
console.error('warning: slow disk'); // stderr
console.log('%s scored %d (%j)', 'Asha', 78, { grade: 'A' }); // format placeholders
process.stdout.write('no newline here');
process.stdout.write('\\n');
console.log('is a terminal:', Boolean(process.stdout.isTTY));
process.exitCode = 3; // exit with a code, without process.exit()
`;
const run = spawnSync(process.execPath, ['-e', childCode], { encoding: 'utf8' });
console.log('--- what the child wrote to stdout ---');
console.log(run.stdout.trimEnd());
console.log('--- what the child wrote to stderr ---');
console.log(run.stderr.trimEnd());
console.log('--- exit code ---');
console.log(run.status);
The parent captures the two streams separately, which is what a shell redirect or a log collector does. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
--- what the child wrote to stdout ---
result: 42
Asha scored 78 ({"grade":"A"})
no newline here
is a terminal: false
--- what the child wrote to stderr ---
warning: slow disk
--- exit code ---
3
Key points
stdout is for data, stderr for errors and diagnostics.
console.log goes to stdout, console.error to stderr.
process.exit can cut pending output on pipes.
Use exitCode and a natural end where possible.
Common mistakes
Writing errors to stdout and breaking pipelines.
Calling process.exit() right after a big write.
Using console.log for high volume logging inside hot loops.
Printing colored text into files.
Follow-ups
Why does process.stdout.write return a boolean?
How can you redirect console output to a file in code?
What is the difference between a TTY and a pipe?
Tips
Say 'data to stdout, messages to stderr'.
Mention exitCode instead of process.exit.
Show the redirect example in words.
76.nodejs-0076Hardsenior
How would you design logging for a production Node.js service: levels, redaction, error details, sampling and request correlation?
Log one structured JSON line per meaningful event, with a level, a stable message, and fields such as request id and duration. Redact secrets by key, serialize errors with their cause chain, sample noisy debug logs, write to stdout, and let the platform ship and rotate them. A logger must never throw or block the request.
Full answer
Design checklist:
Format and destination: JSON lines on stdout. No log files, rotation or shipping inside the app; the platform does that.
Fields: timestamp (ISO or epoch), level, message (a constant text), service and version, environment, and event fields (userId, route, durationMs, statusCode). Use the same field names across services.
Correlation: a request id (and trace id) on every line of a request. AsyncLocalStorage can carry it without passing a logger through every function.
Levels: error means someone should look at it, warn means unexpected but handled, info is business events and one line per request, debug is for investigation and is off by default.
Errors: log the type, message, stack and the cause chain, plus context. Log an error once, at the place that handles it, not at every layer it passes through.
Redaction: remove passwords, tokens, authorization headers, card numbers and personal data. Use a key list and also avoid logging whole request or response bodies.
Volume and cost: sample high-volume low-value lines (for example log 1 in 100 debug lines), cap field sizes, and avoid logging inside tight loops.
Performance: serialize cheaply, write asynchronously, and never await the logger in the request path. A logging failure must not break the request.
Retention and access: decide how long logs are kept and who may read them, since logs often contain personal data.
The code below shows the core of such a logger in a few lines: level filter, redaction, error serialization with cause, and sampling, with an injected clock and random function for repeatable output.
The injected random function makes the sampling repeatable. In the output, two of the four debug lines are dropped. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
{"time":"2026-12-04T10:00:00.000Z","level":"info","msg":"request finished","service":"marks-api","version":"1.4.2","requestId":"req-7","method":"POST","route":"/marks","status":201,"durationMs":18}
{"time":"2026-12-04T10:00:00.000Z","level":"warn","msg":"payload contained a password field","service":"marks-api","version":"1.4.2","requestId":"req-7","body":{"name":"Asha","password":"[redacted]"}}
{"time":"2026-12-04T10:00:00.000Z","level":"error","msg":"save failed","service":"marks-api","version":"1.4.2","requestId":"req-7","err":{"type":"Error","message":"could not save marks","cause":{"type":"Error","message":"connection refused","code":"ECONNREFUSED"}}}
{"time":"2026-12-04T10:00:00.000Z","level":"debug","msg":"cache lookup","service":"marks-api","version":"1.4.2","requestId":"req-7","attempt":1}
{"time":"2026-12-04T10:00:00.000Z","level":"debug","msg":"cache lookup","service":"marks-api","version":"1.4.2","requestId":"req-7","attempt":3}
Key points
Structured JSON lines on stdout, with a constant message and fields.
Correlation ids link all lines of a request.
Redact secrets and avoid logging whole bodies.
Log each error once, with its cause chain.
Sample noisy lines and never block the request.
Common mistakes
Logging the same error at every layer, so one failure creates many lines.
Putting secrets or whole request bodies into logs.
Letting the logger throw on circular objects and crash the request.
Writing logs to local files in a container.
Follow-ups
How would AsyncLocalStorage give every log line a request id?
How do you decide log retention?
What is the difference between logs, metrics and traces?
Tips
Say 'one event, one line, constant message'.
Link correlation ids to AsyncLocalStorage.
Mention cost: logs are expensive at scale.
77.nodejs-0077Easyfresher
What are process signals (SIGINT, SIGTERM, SIGKILL, SIGHUP, SIGUSR1) and how do you handle them in Node.js?
A signal is a small message that the operating system sends to a process. SIGINT is Ctrl+C, SIGTERM is a polite request to stop, SIGHUP means the terminal closed, SIGUSR1 and SIGUSR2 are free for your own use (Node uses SIGUSR1 to start the inspector). SIGKILL and SIGSTOP cannot be caught. Handle signals with process.on('SIGTERM', handler).
Full answer
Signals are how the operating system or another process asks a program to do something.
Common signals:
SIGINT (2): interrupt from the keyboard, Ctrl+C. Node exits by default.
SIGTERM (15): terminate. The normal polite stop, sent by kill <pid>, Docker stop, Kubernetes and process managers. Node exits by default unless you handle it.
SIGKILL (9): immediate stop by the kernel. The process cannot handle, delay or even see it. Orchestrators send it after the grace period.
SIGHUP (1): terminal closed. Daemons often use it to reload configuration.
SIGUSR1: Node reserves it to start the debugger (inspector). SIGUSR2: free for applications, for example to dump a heap snapshot (--heapsnapshot-signal=SIGUSR2).
SIGPIPE: writing to a closed pipe. Node ignores it and gives you an EPIPE error instead.
In Node:
process.on('SIGTERM', fn) registers a handler. Once any handler exists, the default exit behaviour is removed, so your handler must end the process (or start the shutdown) itself.
process.once avoids running a handler twice.
process.kill(pid, 'SIGTERM') sends a signal to any process you own. child.kill('SIGTERM') does it for a child.
On Windows only SIGINT, SIGTERM, SIGHUP and SIGBREAK are partly emulated, and kill() terminates the process unconditionally.
Because SIGKILL cannot be handled, never rely on cleanup code for correctness. Design so that a hard kill is safe: idempotent jobs, transactions and short lock leases.
The child handles SIGTERM and SIGUSR2. With SIGKILL the child gets no chance to print anything, and the parent sees the signal name instead of an exit code. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
SIGUSR2 then SIGTERM -> {
code: 0,
signal: null,
output: 'child: got SIGUSR2, dumping a report\nchild: got SIGTERM, cleaning up'
}
SIGKILL -> { code: null, signal: 'SIGKILL', output: '' }
Key points
SIGTERM asks politely, SIGKILL cannot be caught.
Registering a handler removes the default exit.
SIGUSR1 starts the inspector in Node.
Design for a hard kill as well.
Common mistakes
Adding a SIGTERM handler that never exits the process.
Expecting to catch SIGKILL.
Assuming signal behaviour on Windows is the same as on Linux.
Running the app through a shell script that does not forward signals.
Follow-ups
Why does a container sometimes ignore SIGTERM?
How would you reload config on SIGHUP?
What is the difference between kill and kill -9?
Tips
Give one line for each of the main signals.
Say 'cannot be caught' for SIGKILL.
Mention that handlers replace the default.
78.nodejs-0078Mediummid
What is the difference between process.exit(), process.exitCode, the 'beforeExit' event and the 'exit' event?
process.exitCode sets the code the process will use when it ends naturally. process.exit(code) ends it at once. 'beforeExit' fires when the event loop becomes empty and lets you schedule more work, but not on process.exit() or an uncaught exception. 'exit' fires always at the end and can only run synchronous code.
Full answer
Exit codes tell the caller what happened: 0 means success, any other number means failure. By convention 1 is a general error, 2 is misuse of a command, and 128 + n means "killed by signal n" (143 for SIGTERM, 130 for SIGINT). Node itself uses 1 for uncaught exceptions and unhandled rejections.
Ways to end a process:
Natural end: the event loop has no more work. The exit code is process.exitCode (or 0).
process.exitCode = 2: only sets the code. Pending work continues, and output is flushed. Preferred.
process.exit(2): stops immediately. Pending timers, I/O and unflushed writes are dropped. Use it only after cleanup, or in a deliberate abort.
process.abort(): crashes with a core dump, for diagnostics.
An uncaught exception or unhandled rejection: code 1, unless handlers say otherwise.
Events:
'beforeExit' (code): emitted when the loop empties. A handler can start new asynchronous work, and the process continues. It is not emitted for process.exit() or fatal errors. Beware of infinite loops: a handler that always schedules work never lets the process end.
'exit' (code): emitted when the process is about to end, for every reason except a hard crash or SIGKILL. Only synchronous code is safe. Timers and I/O started here never run, so do not count on promise callbacks either.
'uncaughtException' and 'unhandledRejection': see the error handling questions.
Uses: a command-line tool sets exitCode = 1 when validation fails, so CI stops. A 'exit' handler can write a final synchronous log line or remove a lock file.
javascript
const { spawnSync } = require('node:child_process');
function run(label, code) {
const result = spawnSync(process.execPath, ['-e', code], { encoding: 'utf8' });
console.log(label.padEnd(34), '| code:', result.status, '| stdout:', JSON.stringify(result.stdout.trim()));
}
run('natural end', `console.log('done')`);
run('exitCode set, work continues', `
process.exitCode = 4;
setTimeout(() => console.log('timer still ran'), 20);
`);
run('process.exit drops pending work', `
setTimeout(() => console.log('this timer never runs'), 20);
process.exit(5);
`);
run('exit handler runs sync code only', `
process.on('exit', (code) => {
console.log('exit handler, code', code);
setTimeout(() => console.log('never printed'), 0); // timers and I/O started here never run
});
process.exitCode = 6;
`);
run('beforeExit can schedule more work', `
let rounds = 0;
process.on('beforeExit', () => {
if (rounds++ < 2) {
console.log('beforeExit round', rounds);
setTimeout(() => console.log(' work added in round', rounds), 5);
}
});
`);
run('beforeExit is skipped by process.exit', `
process.on('beforeExit', () => console.log('never printed'));
process.exit(0);
`);
Each case runs in its own child process, so the exit code can be read by the parent. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
natural end | code: 0 | stdout: "done"
exitCode set, work continues | code: 4 | stdout: "timer still ran"
process.exit drops pending work | code: 5 | stdout: ""
exit handler runs sync code only | code: 6 | stdout: "exit handler, code 6"
beforeExit can schedule more work | code: 0 | stdout: "beforeExit round 1\n work added in round 1\nbeforeExit round 2\n work added in round 2"
beforeExit is skipped by process.exit | code: 0 | stdout: ""
Key points
exitCode sets the code. exit() stops immediately.
beforeExit can schedule more work. exit cannot.
128 + signal number is the convention for signals.
Prefer exitCode and a natural end.
Common mistakes
Calling process.exit() right after logging and losing output.
Doing asynchronous clean-up in an 'exit' handler.
Using exit code 0 when a CLI validation failed.
Creating an endless loop with beforeExit.
Follow-ups
What exit code does a process killed by SIGTERM report?
How would you make a CLI return different codes for different errors?
How does a shell script test the exit code?
Tips
Say 'exitCode and let the loop end' as the default advice.
Remember that exit handlers are synchronous.
Know the 128 + n convention.
79.nodejs-0079Hardsenior
How would you build a shutdown manager that closes resources in the right order, with timeouts and no double execution?
Register each resource with a name and a close function when it starts. On a signal, run the close functions in reverse order of creation (stop traffic first, then workers, then databases), give each a timeout, collect errors, run only once, and set an overall deadline. Exit with a code that tells whether the shutdown was clean.
Full answer
A real service holds many resources: an HTTP server, message queue consumers, scheduled jobs, a database pool, a cache connection, open files. Closing them in a careless order causes errors, for example closing the database while requests still use it.
Rules for the order: stop accepting new work first (fail the readiness check, close the listener), then wait for in-flight work, then stop background workers, and last close the shared backends. Registering resources as they start and closing in reverse order gives this naturally, because dependencies start before the things that depend on them.
Features of a good manager:
Idempotent: the second signal (for example an impatient Ctrl+C) does not start a second shutdown. A repeated signal may force exit.
Per-step timeout: a stuck close function must not block the others. Log it and continue.
Overall deadline shorter than the platform grace period (Kubernetes default is 30 seconds). When it expires, exit with a non-zero code.
Error collection: one failing close function does not stop the rest. Report all failures at the end.
Logging: each step logs start, end and duration, so a slow shutdown can be diagnosed.
Exit code: 0 for a clean shutdown, 1 when anything failed or timed out. Use process.exitCode and let the loop end if possible.
Testability: the manager takes a list and a timer function, and does not call process.exit itself, so tests can run it.
This pattern replaces scattered process.on('SIGTERM') handlers across the code base with one place that owns the order.
javascript
class ShutdownManager {
#steps = [];
#running = null;
register(name, close, { timeoutMs = 1000 } = {}) {
this.#steps.push({ name, close, timeoutMs });
}
shutdown(reason) {
if (this.#running) return this.#running; // second signal: same promise, no second run
this.#running = this.#run(reason);
return this.#running;
}
async #run(reason) {
const report = { reason, closed: [], failed: [] };
for (const step of [...this.#steps].reverse()) { // reverse order of creation
let timer;
try {
await Promise.race([
step.close(),
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('timeout after ' + step.timeoutMs + ' ms')), step.timeoutMs); }),
]);
report.closed.push(step.name);
} catch (err) {
report.failed.push(`${step.name}: ${err.message}`); // keep going with the next step
} finally {
clearTimeout(timer);
}
}
report.exitCode = report.failed.length === 0 ? 0 : 1;
return report;
}
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const order = [];
const manager = new ShutdownManager();
// Registered in start-up order.
manager.register('database pool', async () => { await wait(5); order.push('database pool closed'); });
manager.register('queue consumer', async () => { await wait(5); order.push('queue consumer stopped'); });
manager.register('stuck cache client', () => new Promise(() => {}), { timeoutMs: 30 }); // never finishes
manager.register('http server', async () => { await wait(5); order.push('http server closed'); });
async function main() {
// Two signals arrive almost together. Only one shutdown runs.
const first = manager.shutdown('SIGTERM');
const second = manager.shutdown('SIGINT');
console.log('same shutdown for both signals:', first === second);
const report = await first;
console.log('closing order:', order.join(' > '));
console.log('closed:', report.closed);
console.log('failed:', report.failed);
console.log('exit code to use:', report.exitCode);
// In a real service: process.exitCode = report.exitCode;
}
main();
The cache client never finishes closing, so it times out after 30 ms and the manager continues with the remaining steps. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
same shutdown for both signals: true
closing order: http server closed > queue consumer stopped > database pool closed
closed: [ 'http server', 'queue consumer', 'database pool' ]
failed: [ 'stuck cache client: timeout after 30 ms' ]
exit code to use: 1
Key points
Register resources as they start and close in reverse.
Make shutdown idempotent.
Per-step timeouts and an overall deadline.
Collect errors and choose the exit code.
Let tests run the manager without exiting.
Common mistakes
Closing the database before the HTTP server has finished its requests.
Running the shutdown twice when two signals arrive.
Letting one failing close function stop the whole sequence.
Using a deadline longer than the platform grace period.
Follow-ups
How would you test this manager without sending real signals?
How does Kubernetes use preStop hooks and readiness probes here?
What should happen to jobs that are half done?
Tips
Describe the order rule: stop traffic first, shared backends last.
Say 'idempotent' and 'timeouts' within the first two sentences.
Mention the exit code to report health of the shutdown.
80.nodejs-0080Easyfresher
How do you create hashes and HMACs with the crypto module, and how do you verify a webhook signature?
crypto.createHash('sha256') produces a fixed-size fingerprint of data. It cannot be reversed, and the same input always gives the same output. An HMAC (createHmac) mixes in a secret key, so only someone with the key can create or check the value. Services use HMACs to sign webhooks. Verify them with crypto.timingSafeEqual.
Full answer
Hash: a function that turns any amount of data into a short fixed-size value (SHA-256 gives 32 bytes). A tiny change in the input changes the output completely. Uses: checksums, cache keys, file integrity, content addressing. Not for passwords (use scrypt or argon2 for those).
Choosing an algorithm: SHA-256 or SHA-512 for general use. MD5 and SHA-1 are broken for security purposes, though still seen in old checksums.
API:
crypto.createHash('sha256').update(data).digest('hex'). update can be called many times, so a file can be hashed as a stream.
crypto.hash('sha256', data, 'hex') is a one-shot helper in recent Node versions.
Encodings for the result: hex, base64, base64url, or a Buffer when no encoding is given.
HMAC (hash-based message authentication code): hash(key, message) built so that the result proves two things: the message was not changed, and the sender knew the key. API: crypto.createHmac('sha256', secret).update(body).digest('hex').
Webhook verification, step by step:
The provider sends the body and a signature header, computed as HMAC of the raw body with a shared secret.
Your server must use the raw bytes of the body, not the re-serialized JSON. Parsing and stringifying can change spacing and key order.
Compute the HMAC with your copy of the secret.
Compare with crypto.timingSafeEqual on buffers of equal length, never with ===.
Also check a timestamp in the signed data to stop replay of old requests.
Hashing is not encryption. Nothing can be recovered from a hash.
javascript
const crypto = require('node:crypto');
// 1. A hash is deterministic and fixed in size.
const text = 'abc';
console.log('sha256("abc"):', crypto.createHash('sha256').update(text).digest('hex'));
console.log('one-shot helper gives the same:', crypto.hash('sha256', text) === crypto.createHash('sha256').update(text).digest('hex'));
console.log('a small change changes everything:', crypto.createHash('sha256').update('abd').digest('hex').slice(0, 16), '...');
console.log('hash length is always 32 bytes:', crypto.createHash('sha256').update('x'.repeat(10000)).digest().length);
// 2. Hashing in pieces gives the same result as hashing all at once.
const parts = crypto.createHash('sha256').update('a').update('b').update('c').digest('hex');
console.log('hashing in pieces matches:', parts === crypto.createHash('sha256').update('abc').digest('hex'));
// 3. Signing and verifying a webhook body.
const secret = 'shared-webhook-secret';
function sign(rawBody) {
return crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
}
function verify(rawBody, signatureHex) {
const expected = Buffer.from(sign(rawBody), 'hex');
const received = Buffer.from(signatureHex, 'hex');
return expected.length === received.length && crypto.timingSafeEqual(expected, received);
}
const body = '{"event":"result.published","studentId":42}';
const signature = sign(body); // the sender computes this and sends it in a header
console.log('valid signature accepted:', verify(body, signature));
console.log('changed body rejected: ', !verify(body.replace('42', '43'), signature));
console.log('wrong signature rejected:', !verify(body, 'a'.repeat(64)));
The hash of 'abc' is a well-known test value, so you can compare the first line with any SHA-256 reference. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, same on two runs):
sha256("abc"): ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
one-shot helper gives the same: true
a small change changes everything: a52d159f262b2c6d ...
hash length is always 32 bytes: 32
hashing in pieces matches: true
valid signature accepted: true
changed body rejected: true
wrong signature rejected: true
Key points
Hashes are one-way fingerprints. Use SHA-256 or stronger.
HMAC adds a secret key for authentication.
Verify webhooks on the raw body with timingSafeEqual.
Add a timestamp check against replay.
Common mistakes
Using MD5 or SHA-1 for security decisions.
Hashing passwords with plain SHA-256.
Verifying the HMAC over a re-serialized JSON body.
Comparing signatures with === or ==.
Follow-ups
What is a length extension attack, and why does HMAC avoid it?
How do you hash a 5 GB file in Node.js?
How would you rotate a webhook secret without downtime?
Tips
Keep hash, HMAC and encryption separate in your explanation.