Skip to content
  1. Home
  2. Interview Questions
  3. Node.js
Web & Frameworks

50 Node.js Interview Questions and Answers (2026)

The most asked Node.js interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.

Updated November 2026 Reviewed by Abhishek Kumar 60 min read
50Questions
12Freshers
22Intermediate
11Experienced

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 questions

Start here if you are a fresher or switching to Node.js. These fundamentals are asked in almost every first-round and campus interview.

BeginnerNode.js
Quick answerNode.js is a JavaScript runtime built on Chrome's V8 engine. It uses an event-driven, non-blocking I/O model: instead of blocking a thread while waiting for the database or network, it registers a callback and keeps serving other requests.

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.

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?

BeginnerNode.js
Quick answerThe event loop is the mechanism that lets single-threaded JavaScript perform non-blocking operations. It repeatedly checks for completed I/O and timers and runs their callbacks, so the main thread never sits idle waiting.

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.

JavaScript
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)
Likely follow-up questions
  • Inside an I/O callback, which runs first — setTimeout(…, 0) or setImmediate? (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()?

BeginnerNode.js
Quick answerprocess.nextTick() queues a callback to run immediately after the current operation, before promises and before the event loop continues. setImmediate() runs the callback in the check phase of the next loop iteration.

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.

BeginnerNode.js
Quick answerCommonJS 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.

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.

JavaScript
// 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?

BeginnerNode.js
Quick answerUse try/catch around await, return or forward errors to central handlers, and never leave promises unhandled. In Express 5, a rejected promise in a route handler is passed to the error middleware automatically; in Express 4 you must call next(err) or use a wrapper.
JavaScript
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?

BeginnerNode.js
Quick answerMiddleware functions receive (req, res, next) and run in order for each request. They can modify the request or response, end the response, or call next() to pass control on. They are used for logging, authentication, parsing, CORS, rate limiting and error handling (which takes four arguments: err, req, res, next).
JavaScript
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?

BeginnerNode.js
Quick answerStreams process data piece by piece instead of loading it all into memory. There are four types: Readable, Writable, Duplex (both, such as sockets) and Transform (modify data in transit, such as gzip). They are perfect for large files, uploads, video and proxies.
JavaScript
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 streams

How 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?

BeginnerNode.js
Quick answerBuffer represents raw binary data — a fixed-length sequence of bytes outside the V8 heap. Use it for files, network packets, images and encodings (utf8, base64, hex).
JavaScript
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?

BeginnerNode.js
Quick answerRead 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.

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.

JavaScript
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 invalid

How 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?

BeginnerNode.js
Quick answerreadFile loads the whole file into memory before calling back — simple, but risky for large files. createReadStream reads it in chunks (64 KB by default), so memory stays constant and processing can start immediately.

Use readFile for small config files, and streams for logs, uploads and anything that could be large.

BeginnerNode.js
Quick answerREST models resources as URLs and uses HTTP methods for operations: GET /orders, POST /orders, GET /orders/42, PATCH /orders/42, DELETE /orders/42. Good APIs use the correct status codes, consistent JSON errors, validation, pagination, versioning and idempotency for retries.
JavaScript
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 questions

Questions for candidates with 1–3 years of experience — the concepts interviewers use to check that you have actually built things with Node.js.

IntermediateNode.js
Quick answerBackpressure occurs when a writable stream can't consume data as fast as a readable stream produces it. Without handling it, data piles up in memory. write() returns false when the internal buffer is full; you should pause until the 'drain' event fires.

pipe() and stream.pipeline() handle backpressure for you, which is why you should prefer them over manual data event handlers.

IntermediateNode.js
cluster / multiple processesworker_threads
UnitSeparate processes, each with its own memory and event loopThreads inside one process
Use forUsing all CPU cores for an HTTP serverCPU-heavy JavaScript (image processing, parsing, crypto)
SharingVia IPC or external storesSharedArrayBuffer, 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.

JavaScript
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?

IntermediateNode.js
Quick answerOn login, verify the credentials, then sign a short-lived access token (JWT) with a secret or private key. The client sends it as Authorization: Bearer <token>, and middleware verifies the signature and expiry on each request. Use refresh tokens — stored httpOnly, rotated and revocable — to get new access tokens.
JavaScript
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" });
  }
};
Common mistakes
  • 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?

IntermediateNode.js
Quick answerLimit requests per client (by IP, API key or user) over a time window to protect against abuse and overload. Behind multiple instances, keep the counters in a shared store such as Redis, not in process memory.
JavaScript
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?

IntermediateNode.js
  • 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.

JavaScript
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?

IntermediateNode.js
Quick answerlibuv, the C library behind Node's event loop, has a thread pool (4 threads by default, configurable with UV_THREADPOOL_SIZE) for operations without a good non-blocking OS API: file system calls, DNS lookup, crypto (pbkdf2, scrypt) and zlib.

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?

IntermediateNode.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
IntermediateNode.js
Quick answerThe built-in node:test runner (stable since Node 20) and Jest or Vitest for unit tests; Supertest for HTTP integration tests; Testcontainers for real databases; and mocks or fakes for external APIs.
JavaScript
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?

IntermediateNode.js
Quick answerUse WebSockets (the ws library or Socket.IO) for two-way, low-latency communication — chat, live dashboards, multiplayer — or Server-Sent Events for one-way server→client streams such as notifications and AI token streaming. When scaling to multiple instances, use a pub/sub layer (the Redis adapter) so messages reach clients connected to other nodes.
IntermediateNode.js
Quick answerspawn launches a command and streams its stdout and stderr — best for long-running or large-output processes. exec runs a command in a shell and buffers the output into a callback — simple, but has a maxBuffer limit and shell-injection risk. fork spawns a new Node.js process with an IPC channel for send/on('message').
Common mistakes
  • Passing user input to exec. Use execFile/spawn with 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?

IntermediateNode.js
Quick answerEventEmitter is Node's built-in publish/subscribe primitive: objects emit named events and listeners subscribe with on or once. Streams, HTTP servers and sockets are all EventEmitters.
JavaScript
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));
Common mistakes
  • 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?

IntermediateNode.js
Quick answerValidate every external input (body, query, params, headers) against a schema at the edge, and reject bad data with a 400 and clear messages. Libraries: zod, joi, ajv (JSON Schema — Fastify uses it natively).
JavaScript
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);
IntermediateNode.js
Quick answerCORS (Cross-Origin Resource Sharing) is a browser security mechanism: a page on app.example.com can call an API on api.example.com only if the API responds with headers such as Access-Control-Allow-Origin that permit that origin. Non-simple requests trigger an OPTIONS preflight first.
JavaScript
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"],
}));
Common mistakes
  • 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?

IntermediateNode.js
Quick answerCreate one connection pool per process at startup and reuse it for every request. Opening a connection per request is slow and exhausts the database's connection limit. Size the pool to your database's capacity divided by the number of instances, and always use parameterised queries.
JavaScript
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?

IntermediateNode.js
Quick answerThey don't exist in ESM. Use import.meta.dirname and import.meta.filename (Node.js 20.11+), or derive them from import.meta.url.
JavaScript
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?

IntermediateNode.js
Quick answerDon't run long jobs inside the request/response cycle. Push them to a queue (BullMQ on Redis, SQS, RabbitMQ) and process them in separate worker processes with retries, backoff and dead-letter handling. For scheduled jobs, use the queue's repeatable jobs or a cron scheduler — and make sure only one instance runs each schedule.
JavaScript
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?

IntermediateNode.js
Quick answerUse a structured JSON logger (pino or winston) with levels, request IDs and no secrets or PII. Write logs to stdout and let the platform ship them to a central store (ELK, Loki, CloudWatch). console.log is synchronous to terminals and unstructured.
JavaScript
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?

IntermediateNode.js
Quick answerThe first require() of a module executes it and stores module.exports in require.cache, keyed by the resolved file path. Later require() calls return the same cached object, which is why modules behave like singletons (a shared database client, for example). Circular requires receive a partially filled exports object.
IntermediateNode.js
Quick answerutil.promisify converts a Node-style callback function — (err, result) as the last argument — into a function that returns a promise, so you can await it. Most core APIs now have promise versions (fs/promises, timers/promises), but promisify remains useful for older libraries.
JavaScript
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?

IntermediateNode.js
Quick answerTerminate TLS at the proxy (Nginx, a cloud load balancer), forward to Node over HTTP, and tell Express to trust the proxy so req.ip, req.protocol and secure cookies work correctly. Add health-check endpoints, and set keep-alive timeouts slightly higher than the load balancer's idle timeout to avoid intermittent 502 errors.
JavaScript
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?

IntermediateNode.js
Quick answernode:fs and fs/promises (files), node:path (paths), node:http / https (servers and clients), node:stream (streams), node:events (EventEmitter), node:crypto (hashing, random UUIDs, encryption), node:os (system info), node:child_process, node:worker_threads, node:url, node:zlib, node:test (test runner) and node:util. Modern Node also has a global fetch, WebSocket client and Web Crypto.

Advanced Node.js Interview Questions for Experienced Developers

11 questions

Senior-level Node.js questions on internals, performance, design and trade-offs — typical for 3, 5 and 7+ years of experience.

AdvancedNode.js
Quick answerAll JavaScript callbacks share the main thread. A 2-second synchronous computation — big JSON parsing, image resizing, bcrypt with a high cost, a catastrophic regex — blocks every other request for those 2 seconds, so latency spikes for all users.

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.

JavaScript
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?

AdvancedNode.js
  1. Confirm it with metrics: heap used grows steadily across GC cycles (process.memoryUsage(), APM tools).
  2. Take heap snapshots (--inspect + Chrome DevTools, node --heapsnapshot-signal=SIGUSR2, or v8.writeHeapSnapshot()) at intervals and compare them; look for growing retained sizes.
  3. Common causes: unbounded in-memory caches or maps, global arrays, listeners never removed, closures holding large objects, timers never cleared.
  4. 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?

AdvancedNode.js
  • 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?

AdvancedNode.js
Quick answerOn SIGTERM: stop accepting new connections, finish in-flight requests, close database pools and queues, then exit. Add a hard timeout so a stuck connection can't block the deploy forever.
JavaScript
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);
AdvancedNode.js
Quick answerAsyncLocalStorage (from node:async_hooks) keeps per-request context — request ID, user, tenant, trace ID — across await boundaries without passing it through every function. It is the basis of request-scoped logging and tracing.
JavaScript
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?

AdvancedNode.js
Quick answerStream uploads instead of buffering them in memory; enforce size limits and type checks (inspect magic bytes, not just the extension); store files in object storage (S3, GCS) under random keys; scan them for malware where needed; and never serve uploads from your application's own origin. For large files, issue pre-signed URLs so clients upload directly to storage.

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?

AdvancedNode.js
  • 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
AdvancedNode.js
ExpressFastifyNestJS
StyleMinimal, unopinionatedMinimal, plugin-based, schema-firstOpinionated architecture, DI, modules
PerformanceGoodVery highDepends on the adapter (Express or Fastify)
ValidationBYO libraryBuilt-in JSON SchemaPipes and class-validator
Best forSimple APIs, huge ecosystemHigh-throughput APIsLarge TypeScript teams, enterprise apps
AdvancedNode.js
Quick answerRecent 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.

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?

AdvancedNode.js
Quick answerAccept an Idempotency-Key header. Store the key together with the request hash and the eventual response. On a retry with the same key, return the stored response instead of processing again. Use a unique constraint or atomic insert so concurrent duplicates can't both proceed.
JavaScript
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?

AdvancedNode.js
Quick answerA modular monolith is one deployable application with strict internal module boundaries — simple to run, debug and deploy, with no network calls between modules. Microservices are separately deployable services that communicate over the network — independent scaling and deployment, but more operational overhead: network failures, distributed tracing, data consistency.

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 questions

Hands-on Node.js programs that are asked in coding rounds and machine tests. Read the code, then try writing it yourself without looking.

CodingNode.js
Quick answerWrap the operation in an AbortController timeout, retry on failure with exponential backoff, and give up after N attempts.
JavaScript
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()));
CodingNode.js
Quick answerThe built-in http module gives you the raw request and response objects; routing and body parsing are up to you.
JavaScript
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"));
CodingNode.js
Quick answerUse readline over a read stream, so memory stays constant regardless of file size.
JavaScript
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));
CodingNode.js
Quick answerRun async tasks with at most N in flight at once — for example, to avoid overwhelming an API with 10,000 simultaneous requests.
JavaScript
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()));
CodingNode.js
Quick answerA Map remembers insertion order, so deleting and re-inserting a key on access moves it to the "most recent" end, and the first key is always the least recently used.
JavaScript
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 →

Node.js interview FAQ

What Node.js questions are asked for experienced developers?
Event loop phases and libuv, process.nextTick vs setImmediate, streams and backpressure, worker threads vs cluster, memory leaks and heap snapshots, error handling and unhandled rejections, security (injection, prototype pollution, dependency risk), performance profiling, graceful shutdown and scaling behind a load balancer.
Is Node.js single-threaded?
JavaScript in Node.js runs on a single main thread, but Node is not single-threaded overall: libuv uses a thread pool for file system, DNS and crypto work, the OS handles network I/O asynchronously, and you can use worker_threads for CPU-heavy JavaScript.
Express vs NestJS vs Fastify — which should I know?
Express is the most widely known and still asked about. Fastify is faster with built-in schema validation. NestJS adds an opinionated, Angular-like architecture with dependency injection and is popular in enterprise TypeScript teams. Know Express well and the trade-offs of the others.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.