A single process can therefore handle thousands of concurrent connections with little memory, which makes it ideal for APIs, chat, streaming and proxies. It is not ideal for long CPU-bound work on the main thread.
Key takeaways
- 50 Node.js interview questions, grouped by level: freshers, intermediate, experienced and coding.
- Every answer starts with a one-line “Quick answer” you can say out loud, followed by the explanation and runnable code.
- Use the filter bar to practise only the level you are interviewing for, then test yourself with the free Node.js quiz.
What is Node.js, and why do interviewers ask about it?
Node.js runs JavaScript on the server using Google's V8 engine and an event-driven, non-blocking I/O model. It powers APIs, real-time apps, BFFs (backend-for-frontend), serverless functions and developer tooling at companies of every size.
Node.js interviews test whether you understand the runtime, not just Express syntax: the event loop and libuv, streams and backpressure, clustering and worker threads, error handling in async code, security, and how to scale and debug a production service.
Why companies hire for Node.js
- Huge demand for full-stack JavaScript and TypeScript developers
- One language across frontend, backend and tooling
- Excellent for I/O-heavy APIs, real-time features and microservices
- Massive npm ecosystem and first-class serverless support
Basic Node.js Interview Questions for Freshers
12 questionsStart here if you are a fresher or switching to Node.js. These fundamentals are asked in almost every first-round and campus interview.
How interviewers ask it“In simple words, what is the event loop? Explain it like you would to a new teammate.”
What is the event loop in Node.js?
Its phases, in order: timers (setTimeout/setInterval) → pending callbacks → poll (retrieve I/O events, run I/O callbacks) → check (setImmediate) → close callbacks. Between callbacks, Node drains the process.nextTick queue and then the promise microtask queue.
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");
// sync, nextTick, promise, then timeout/immediate (order of these two can vary in the main module)- Inside an I/O callback, which runs first —
setTimeout(…, 0)orsetImmediate? (setImmediate, because the check phase comes right after poll.)
How interviewers ask it“How is process.nextTick() different from setImmediate(), and when does the difference matter in practice?”
What is the difference between process.nextTick() and setImmediate()?
Overusing nextTick recursively can starve I/O, because the loop can't move on until the queue is empty. Prefer setImmediate or queueMicrotask unless you specifically need to run before anything else.
package-lock.json pins the exact dependency tree for reproducible installs — commit it and use npm ci in CI.
CommonJS uses require() / module.exports and loads synchronously. ES modules use import / export, support top-level await and enable tree-shaking. Use ESM by setting "type": "module" in package.json or naming files .mjs.
// ESM (recommended for new code)
import express from "express";
import { readFile } from "node:fs/promises";
const config = JSON.parse(await readFile("./config.json", "utf8"));
// CommonJS
const path = require("node:path");
module.exports = { join: path.join };How interviewers ask it“Suppose you need to handle errors in asynchronous Node.js code — how do you approach it, and what can go wrong?”
How do you handle errors in asynchronous Node.js code?
app.get("/users/:id", async (req, res, next) => {
try {
const user = await db.users.findById(req.params.id);
if (!user) return res.status(404).json({ error: "Not found" });
res.json(user);
} catch (err) {
next(err);
}
});
app.use((err, req, res, next) => { // central error handler
req.log?.error(err);
res.status(err.status || 500).json({ error: "Internal error" });
});
process.on("unhandledRejection", (r) => { console.error(r); process.exit(1); });How interviewers ask it“In simple words, what is middleware in Express? Explain it like you would to a new teammate.”
What is middleware in Express?
const requireAuth = (req, res, next) => {
const token = req.headers.authorization?.replace("Bearer ", "");
if (!token) return res.status(401).json({ error: "Unauthorized" });
req.user = verifyJwt(token);
next();
};
app.use(express.json());
app.get("/me", requireAuth, (req, res) => res.json(req.user));How interviewers ask it“In simple words, what are streams? Explain it like you would to a new teammate.”
What are streams in Node.js?
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";
import { pipeline } from "node:stream/promises";
await pipeline(
createReadStream("access.log"),
createGzip(),
createWriteStream("access.log.gz")
); // handles backpressure and errors, and cleans up the streamsHow interviewers ask it“In simple words, what is the Buffer class? Explain it like you would to a new teammate.”
What is the Buffer class?
const buf = Buffer.from("InterviewPitch", "utf8");
console.log(buf.length); // 14 bytes
console.log(buf.toString("base64")); // SW50ZXJ2aWV3UGl0Y2g=How interviewers ask it“How would you read environment variables and configuration safely? Walk me through your approach.”
How do you read environment variables and configuration safely?
Read them from process.env, validate them once at startup, and fail fast if any are missing. Keep secrets out of source control. Node.js 20.6+ can load .env files natively with --env-file=.env.
import { z } from "zod";
const Env = z.object({
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.string().url(),
JWT_SECRET: z.string().min(32),
});
export const env = Env.parse(process.env); // throws with a clear message if invalidHow interviewers ask it“How is fs.readFile different from fs.createReadStream, and when does the difference matter in practice?”
What is the difference between fs.readFile and fs.createReadStream?
Use readFile for small config files, and streams for logs, uploads and anything that could be large.
const router = express.Router();
router.get("/orders", async (req, res) => {
const { cursor, limit = 20 } = req.query;
const page = await Orders.list({ cursor, limit: Math.min(+limit, 100) });
res.json({ data: page.items, nextCursor: page.nextCursor });
});
router.post("/orders", validate(OrderSchema), async (req, res) => {
const order = await Orders.create(req.body, req.get("Idempotency-Key"));
res.status(201).location(`/orders/${order.id}`).json(order);
});Intermediate Node.js Interview Questions
22 questionsQuestions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with Node.js.
pipe() and stream.pipeline() handle backpressure for you, which is why you should prefer them over manual data event handlers.
| cluster / multiple processes | worker_threads | |
|---|---|---|
| Unit | Separate processes, each with its own memory and event loop | Threads inside one process |
| Use for | Using all CPU cores for an HTTP server | CPU-heavy JavaScript (image processing, parsing, crypto) |
| Sharing | Via IPC or external stores | SharedArrayBuffer, transferable objects |
In containers, teams usually run one process per container and scale replicas with Kubernetes or a PM2-style process manager, rather than using cluster.
import { Worker } from "node:worker_threads";
function runHeavy(data) {
return new Promise((resolve, reject) => {
const w = new Worker(new URL("./heavy.js", import.meta.url), { workerData: data });
w.once("message", resolve);
w.once("error", reject);
});
}How interviewers ask it“Can you implement JWT authentication in a Node.js API? Then walk me through the edge cases you would test.”
How do you implement JWT authentication in a Node.js API?
import jwt from "jsonwebtoken";
const sign = (user) =>
jwt.sign({ sub: user.id, role: user.role }, env.JWT_SECRET, { expiresIn: "15m", algorithm: "HS256" });
const auth = (req, res, next) => {
try {
const token = req.headers.authorization?.split(" ")[1];
req.user = jwt.verify(token, env.JWT_SECRET, { algorithms: ["HS256"] });
next();
} catch {
res.status(401).json({ error: "Invalid or expired token" });
}
};- Putting sensitive data in the JWT payload — it is only base64-encoded, not encrypted.
How interviewers ask it“Live coding: Implement rate limiting in Node.js. Talk me through your approach first.”
How do you implement rate limiting in Node.js?
import rateLimit from "express-rate-limit";
app.use("/api/", rateLimit({
windowMs: 60_000,
limit: 100, // 100 requests per minute per key
standardHeaders: "draft-7",
legacyHeaders: false,
}));Algorithms worth naming: fixed window, sliding window and token bucket.
How interviewers ask it“How would you cache data in a Node.js application? Walk me through your approach.”
How do you cache data in a Node.js application?
- In-process LRU cache for small, hot, per-instance data (fastest, but not shared between instances)
- Redis for shared caching, sessions and rate limits across instances
- HTTP caching (
Cache-Control,ETag) and a CDN for public responses
Use cache-aside: read from the cache, on a miss load from the database, then set with a TTL. Invalidate on writes, and protect against stampedes with request coalescing or locks.
async function getProduct(id) {
const key = `product:${id}`;
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
const product = await db.products.findById(id);
await redis.set(key, JSON.stringify(product), { EX: 300 });
return product;
}How interviewers ask it“Explain the libuv thread pool in Node.js in detail — what should a new team member understand about it?”
What is the libuv thread pool?
Network sockets do not use the pool. If many slow fs or crypto calls saturate the pool, unrelated fs calls start waiting too — a classic hidden bottleneck.
How interviewers ask it“How would you prevent common security vulnerabilities? Walk me through your approach.”
How do you prevent common security vulnerabilities in Node.js?
- Injection: use parameterised queries or ORMs; validate all input (zod, joi)
- XSS and headers: set security headers with Helmet, and escape output
- Prototype pollution: don't deep-merge untrusted objects; use schema validation
- Dependency risk:
npm audit, lockfiles, Dependabot/Renovate, minimal packages - Secrets: use environment variables or a secrets manager, never source code or logs
- DoS: body size limits, rate limiting, timeouts, avoid catastrophic regexes
- Auth: hash passwords with bcrypt or argon2; use secure, httpOnly, sameSite cookies
import { test } from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { app } from "../app.js";
test("GET /health returns 200", async () => {
const res = await request(app).get("/health");
assert.equal(res.status, 200);
});How interviewers ask it“Live coding: Build real-time features in Node.js. Talk me through your approach first.”
How do you build real-time features in Node.js?
- Passing user input to
exec. UseexecFile/spawnwith an argument array instead.
How interviewers ask it“How would you explain an EventEmitter to a junior engineer, and what do people most often get wrong?”
What is an EventEmitter?
import { EventEmitter } from "node:events";
class OrderService extends EventEmitter {
place(order) {
// ...save the order...
this.emit("order:placed", order);
}
}
const svc = new OrderService();
svc.on("order:placed", (o) => sendEmail(o.userEmail));- Adding listeners in a loop without removing them — Node warns about a "possible EventEmitter memory leak" after 10 listeners.
How interviewers ask it“Suppose you need to validate request data in a Node.js API — how do you approach it, and what can go wrong?”
How do you validate request data in a Node.js API?
import { z } from "zod";
const CreateUser = z.object({
email: z.string().email(),
name: z.string().min(2).max(80),
age: z.number().int().min(16).optional(),
});
const validate = (schema) => (req, res, next) => {
const r = schema.safeParse(req.body);
if (!r.success) return res.status(400).json({ errors: r.error.flatten() });
req.body = r.data;
next();
};
app.post("/users", validate(CreateUser), createUser);import cors from "cors";
app.use(cors({
origin: ["https://interviewpitch.com", "https://admin.interviewpitch.com"],
credentials: true, // allow cookies; requires explicit origins, not "*"
methods: ["GET", "POST", "PATCH", "DELETE"],
}));- Thinking CORS protects your API from attackers — it only restricts browsers. Servers and curl ignore it, so you still need authentication.
How interviewers ask it“Suppose you need to connect to a database efficiently from Node.js — how do you approach it, and what can go wrong?”
How do you connect to a database efficiently from Node.js?
import pg from "pg";
export const pool = new pg.Pool({ connectionString: env.DATABASE_URL, max: 10, idleTimeoutMillis: 30_000 });
export async function getUser(id) {
const { rows } = await pool.query("SELECT id, email FROM users WHERE id = $1", [id]);
return rows[0];
}In serverless environments, use a connection proxy or pooler (PgBouncer, RDS Proxy) because each function instance would otherwise open its own connections.
How interviewers ask it“Suppose you need to get __dirname and __filename in ES modules — how do you approach it, and what can go wrong?”
How do you get __dirname and __filename in ES modules?
import path from "node:path";
import { fileURLToPath } from "node:url";
const dir = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
const configPath = path.join(dir, "config.json");How interviewers ask it“How would you run background jobs and scheduled tasks? Walk me through your approach.”
How do you run background jobs and scheduled tasks in Node.js?
import { Queue, Worker } from "bullmq";
const emails = new Queue("emails", { connection });
await emails.add("welcome", { userId: 42 }, { attempts: 5, backoff: { type: "exponential", delay: 1000 } });
new Worker("emails", async (job) => sendWelcomeEmail(job.data.userId), { connection, concurrency: 10 });How interviewers ask it“Suppose you need to log properly in a production Node.js service — how do you approach it, and what can go wrong?”
How do you log properly in a production Node.js service?
import pino from "pino";
export const logger = pino({ level: process.env.LOG_LEVEL ?? "info", redact: ["req.headers.authorization", "password"] });
logger.info({ orderId: 991, amount: 499 }, "order placed");
// {"level":30,"time":...,"orderId":991,"amount":499,"msg":"order placed"}How interviewers ask it“How does require() caching work under the hood? Take me through it step by step.”
How does require() caching work in CommonJS?
import { promisify } from "node:util";
import { exec } from "node:child_process";
const execAsync = promisify(exec);
const { stdout } = await execAsync("git rev-parse --short HEAD");How interviewers ask it“Suppose you need to run a Node.js app behind a reverse proxy or load balancer — how do you approach it, and what can go wrong?”
How do you run a Node.js app behind a reverse proxy or load balancer?
app.set("trust proxy", 1); // trust the first proxy hop
app.get("/healthz", (req, res) => res.send("ok"));
const server = app.listen(3000);
server.keepAliveTimeout = 65_000; // longer than the LB idle timeout (often 60 s)
server.headersTimeout = 66_000;How interviewers ask it“Explain the most useful Node.js built-in modules to know in detail — what should a new team member understand about them?”
What are the most useful Node.js built-in modules to know?
Advanced Node.js Interview Questions for Experienced Developers
11 questionsSenior-level Node.js questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.
Fixes: move the work to worker_threads or a separate job queue (BullMQ), use async or streaming APIs, break the work into chunks with setImmediate, offload to native or other services, and monitor event-loop lag.
import { monitorEventLoopDelay } from "node:perf_hooks";
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
setInterval(() => console.log("p99 loop delay ms", h.percentile(99) / 1e6), 10_000);How interviewers ask it“Coding-round task — find a memory leak in a Node.js service. Explain your approach before you write the code.”
How do you find a memory leak in a Node.js service?
- Confirm it with metrics: heap used grows steadily across GC cycles (
process.memoryUsage(), APM tools). - Take heap snapshots (
--inspect+ Chrome DevTools,node --heapsnapshot-signal=SIGUSR2, orv8.writeHeapSnapshot()) at intervals and compare them; look for growing retained sizes. - Common causes: unbounded in-memory caches or maps, global arrays, listeners never removed, closures holding large objects, timers never cleared.
- Fix the issue: bounded LRU caches,
WeakMap, cleaning up listeners, streaming instead of buffering.
How interviewers ask it“Suppose you need to scale a Node.js application — how do you approach it, and what can go wrong?”
How do you scale a Node.js application?
- Vertically: use all cores (one process per core, or multiple containers)
- Horizontally: stateless instances behind a load balancer; sessions in Redis or JWTs; files in object storage
- Offload work: queues for slow tasks, worker threads for CPU work
- Data layer: connection pooling, read replicas, caching
- Edge: CDN for static and cacheable responses
- Observability: metrics, tracing (OpenTelemetry), event-loop lag alerts
How interviewers ask it“Can you implement graceful shutdown in Node.js? Then walk me through the edge cases you would test.”
How do you implement graceful shutdown in Node.js?
const server = app.listen(env.PORT);
async function shutdown(signal) {
console.log(`${signal} received, shutting down`);
server.close(async () => { // stop new connections, wait for in-flight
await Promise.allSettled([db.end(), redis.quit()]);
process.exit(0);
});
setTimeout(() => process.exit(1), 15_000).unref(); // force exit
}
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
export const ctx = new AsyncLocalStorage();
app.use((req, res, next) => ctx.run({ requestId: randomUUID() }, next));
export const log = (msg) => console.log(JSON.stringify({ requestId: ctx.getStore()?.requestId, msg }));How interviewers ask it“Suppose you need to handle file uploads securely in Node.js — how do you approach it, and what can go wrong?”
How do you handle file uploads securely in Node.js?
How interviewers ask it“Walk me through the main performance tips for Node.js APIs. Where do they come up in real systems?”
What are the main performance tips for Node.js APIs?
- Keep the event loop free: no synchronous fs or crypto calls in request paths
- Reuse connections: database pools, HTTP keep-alive agents
- Choose fast serialisation and frameworks where it matters (for example, Fastify's schema-based serialisation)
- Cache aggressively and paginate everything
- Compress responses at the proxy or CDN, not in Node
- Profile with
--cpu-prof, Clinic.js or 0x flame graphs, and load-test with k6 or autocannon
| Express | Fastify | NestJS | |
|---|---|---|---|
| Style | Minimal, unopinionated | Minimal, plugin-based, schema-first | Opinionated architecture, DI, modules |
| Performance | Good | Very high | Depends on the adapter (Express or Fastify) |
| Validation | BYO library | Built-in JSON Schema | Pipes and class-validator |
| Best for | Simple APIs, huge ecosystem | High-throughput APIs | Large TypeScript teams, enterprise apps |
Recent Node.js versions can run .ts files directly through type stripping: the type annotations are removed at load time, with no type checking. You still run tsc --noEmit (or your editor) for type checks, and many teams use tsx or a bundler for development. Features that need code generation, such as enums, require a transform flag or a build step.
How interviewers ask it“How would you design an idempotent payment or order API? Walk me through your approach.”
How do you design an idempotent payment or order API?
app.post("/payments", async (req, res) => {
const key = req.get("Idempotency-Key");
if (!key) return res.status(400).json({ error: "Idempotency-Key required" });
const existing = await db.idem.find(key);
if (existing) return res.status(existing.status).json(existing.body);
await db.idem.insertPending(key); // unique constraint blocks duplicates
const result = await payments.charge(req.body);
await db.idem.complete(key, 201, result);
res.status(201).json(result);
});How interviewers ask it“Can you compare microservices and a modular monolith? Where do people usually confuse them?”
What is the difference between microservices and a modular monolith in Node.js?
Start with a modular monolith, and split out services only where independent scaling, team ownership or deployment cadence justify it.
Node.js Coding Interview Questions (Programs with Code)
5 questionsHands-on Node.js programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.
async function withRetry(fn, { retries = 3, timeoutMs = 2000, baseMs = 200 } = {}) {
for (let attempt = 0; ; attempt++) {
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), timeoutMs);
try {
return await fn(ac.signal);
} catch (err) {
if (attempt >= retries) throw err;
await new Promise((r) => setTimeout(r, baseMs * 2 ** attempt));
} finally {
clearTimeout(timer);
}
}
}
const data = await withRetry((signal) => fetch("https://api.example.com/data", { signal }).then((r) => r.json()));import http from "node:http";
const server = http.createServer(async (req, res) => {
if (req.method === "GET" && req.url === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ ok: true }));
}
if (req.method === "POST" && req.url === "/echo") {
let body = "";
for await (const chunk of req) body += chunk; // the request is a readable stream
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(body);
}
res.writeHead(404).end();
});
server.listen(3000, () => console.log("listening on :3000"));import { createReadStream } from "node:fs";
import readline from "node:readline";
async function sumColumn(path, col) {
const rl = readline.createInterface({ input: createReadStream(path), crlfDelay: Infinity });
let total = 0, header = true;
for await (const line of rl) {
if (header) { header = false; continue; }
total += Number(line.split(",")[col]) || 0;
}
return total;
}
console.log(await sumColumn("sales.csv", 3));async function pool(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
async function run() {
while (next < items.length) {
const i = next++;
results[i] = await worker(items[i], i);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run));
return results;
}
const pages = await pool(urls, 5, (u) => fetch(u).then((r) => r.text()));class LRU {
constructor(max = 500, ttlMs = 60_000) { this.max = max; this.ttl = ttlMs; this.map = new Map(); }
get(k) {
const e = this.map.get(k);
if (!e) return undefined;
if (Date.now() > e.exp) { this.map.delete(k); return undefined; }
this.map.delete(k); this.map.set(k, e); // mark as recently used
return e.v;
}
set(k, v) {
this.map.delete(k);
this.map.set(k, { v, exp: Date.now() + this.ttl });
if (this.map.size > this.max) this.map.delete(this.map.keys().next().value); // evict LRU
}
}Practise with the free Node.js quiz
Multiple-choice questions with instant feedback. Takes about 10 minutes and shows exactly which concepts to revise.
Start the Node.js quiz →