Node.jsBy Experience Levelintermediate

Node JS Interview Questions and Answers

25 Node.js interview questions from event loop basics to slow services, memory leaks and safe retries.

Published
TL;DR – Quick Answer

Node.js interviews focus on the event loop, async code, modules, Express, streams and security. Freshers explain how a request is handled. With 5 years or more, expect questions on slow services, memory leaks, shutdown, retries and design choices.

On This Page

Node JS interview questions test whether you understand async code, the event loop, modules, streams and web APIs. Juniors explain how Node works. Senior developers explain why a service became slow and how they made it safe. Below are 25 questions, from easy to hard.

How to prepare for Node JS interview questions

Node runs JavaScript, so weak promise knowledge shows quickly. Revise promises and async/await questions first. If you have not built a server yet, finish the Node JS tutorial.

Experience What interviewers check
Fresher to 1 year How Node works, npm, modules, Express routes
2 to 4 years Errors, streams, login, testing
5 years Slow services, memory, shutdown
Senior developer System design, live problems, trade-offs

Node JS basics for freshers

Q1. What is Node.js?

30-second answer: Node.js is a program that runs JavaScript outside the browser. It uses the V8 engine to run code. It uses a library called libuv for the event loop and much of its async work.

Node suits APIs, chat apps and tools that spend much time waiting for networks or files. It is neither a language nor a framework.

Q2. Is Node.js single-threaded?

30-second answer: Your JavaScript normally runs on one main thread. Node also uses the operating system and a small pool of helper threads. You can add worker threads for heavy JavaScript calculation.

Interview note: "Node has only one thread" is too simple. The helper pool has four threads by default. Some file, DNS, crypto and compression work uses it.

Q3. What is the event loop?

30-second answer: The event loop picks the next ready callback to run. It moves through phases such as timers, poll and check. If one callback runs too long, every other request waits.

The operating system usually watches network connections. Node does not create one JavaScript thread per request.

Q4. Predict the output of this code.

30-second answer: Normal code runs first. In a CommonJS file, process.nextTick runs next, then promise callbacks, then timers.

setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("tick"));
console.log("main");
// main
// tick
// promise
// timeout

Common mistake: Saying setTimeout(0) always beats setImmediate in the main file. That order is not fixed. Inside a file-read callback, setImmediate runs first.

Q5. What is the difference between CommonJS and ES modules?

30-second answer: CommonJS uses require and module.exports. ES modules use import and export, and they allow await outside a function. Use "type": "module" in package.json, or the .mjs file ending, for ES modules.

Choose one style for a new project. Mixing both can make imports confusing.

Q6. What do package.json and the lock file do?

30-second answer: package.json lists project details, scripts and allowed library versions. package-lock.json records the exact versions installed. npm ci installs from the lock file and fails if the two files do not match.

Use npm ci on build servers so every build gets the same libraries.

Q7. What is the difference between dependencies and devDependencies?

30-second answer: Libraries needed by the running app go in dependencies. Tools needed only to build or test go in devDependencies. A production install can skip the second group.

Express is usually a dependency. A test runner is usually a development dependency.

Q8. What is middleware in Express?

30-second answer: Middleware is a function that runs between the request and the final response. It can read data, change the response, finish it, or call next(). Express runs middleware in the order you add it.

function requestLog(req, res, next) {
  console.log(req.method, req.url);
  next();
}

If it neither responds nor calls next, the request hangs. A common next question is the difference between GET and POST.

Q9. How do you read environment values?

30-second answer: Use process.env. Each value is either text or undefined, so check it when the app starts. Never commit passwords or keys.

const port = Number(process.env.PORT ?? 3000);
if (!Number.isInteger(port)) throw new Error("Bad PORT");

This code stops at startup instead of failing later with a confusing message.

Questions for two to four years of experience

Q10. How do you handle errors in async code?

30-second answer: Await the promise. Use try/catch where you can recover or add useful detail. Otherwise, let the error reach one central handler, and hide internal details from users.

Express 5 sends rejected route promises to error middleware. In Express 4, you pass the error to next yourself.

Q11. What is the difference between Promise.all and Promise.allSettled?

30-second answer: Promise.all fails as soon as one promise fails. allSettled waits for all and reports each result. Use all when you need every result, and allSettled when some results are still useful.

Promise.allSettled([
  Promise.resolve("ok"),
  Promise.reject(new Error("failed")),
]).then(r => console.log(r.map(x => x.status)));
// [ 'fulfilled', 'rejected' ]

After a failure, Promise.all does not cancel the other work.

Q12. What are streams and backpressure?

30-second answer: Streams handle data in pieces. Backpressure means slowing the reader when the writer cannot keep up. The pipeline function handles both errors and backpressure.

import { pipeline } from "node:stream/promises";
import { createReadStream, createWriteStream } from "node:fs";
import { createGzip } from "node:zlib";

await pipeline(
  createReadStream("app.log"),
  createGzip(),
  createWriteStream("app.log.gz"),
);

Memory use stays low even when the file is large.

Q13. What is a Buffer?

30-second answer: A Buffer stores raw bytes. Use it for files, network data and other binary data. Choose the right text encoding when you convert it.

const b = Buffer.from("é", "utf8");
console.log(b.length);   // 2
console.log("é".length); // 1

One character may need more than one byte. This matters when you set size limits.

Q14. How does EventEmitter work?

30-second answer: It calls listener functions when a named event happens. Listeners run in the order they were added, one after another. An error event with no listener throws an error.

Remove listeners you no longer need. Adding one per request is a common memory leak.

Q15. How would you secure a Node API?

30-second answer: Check all input, use HTTPS, check permission on each protected action, and limit request size and rate. Keep secrets out of code. Use database queries that keep values separate from SQL text.

Explain authentication vs authorization separately. Being logged in does not mean a user may read every record.

Q16. JWT or server session: which do you choose?

30-second answer: A session is easy to cancel because the server stores it. A JWT can be checked without a session lookup, but it normally works until it expires. Choose based on how quickly you must cancel access.

Anyone holding a normal signed JWT can read its contents. The signature stops changes, but it does not hide data.

Q17. How do you test a Node service?

30-second answer: Test business rules on their own. Test routes with a real test database where practical, and add a few full-flow tests. Include timeouts, bad input and repeated requests.

Node has a built-in node:test module. Jest and Vitest are other common choices.

Node JS interview questions and answers for 5 years experience

Node JS interview questions for 5 years experience expect a clear order of checks. Say what you would measure before what you would change.

Q18. CPU is high and requests are slow. What do you do?

30-second answer: I check recent changes, slow routes and event loop delay. Then I take a CPU profile when safe. I look for large JSON work, slow regex, blocking calls or big loops.

Fix the slow part, or move it to a worker or separate job. Adding async to a calculation loop does not stop it from blocking.

Q19. How do you find a memory leak?

30-second answer: Watch how much memory remains after garbage collection. If it keeps rising, compare heap snapshots and see what still holds the objects. Look at caches, listeners and closures first.

Give caches a size limit and an expiry time. A restart only hides the issue for a while.

Pro tip: Check both JavaScript heap memory and total process memory. Buffers can use memory outside the heap.

Q20. Compare cluster and worker threads.

30-second answer: Cluster starts several Node processes that can share a port. Worker threads run JavaScript in extra threads inside one process. Use processes to serve more requests, and workers for heavy calculation.

With containers, many teams run one Node process per container and let the platform add copies.

Q21. How do you shut down without losing requests?

30-second answer: When SIGTERM arrives, mark the app as not ready and stop taking requests. Finish active ones, close database connections and exit. Set a time limit so it cannot wait forever.

process.once("SIGTERM", () => {
  server.close(() => process.exit(0));
  setTimeout(() => process.exit(1), 10000).unref();
});

Here, server is your running HTTP server. The timer exits with an error after ten seconds.

Node JS interview questions for senior developer roles

Q22. How would you design retries?

30-second answer: Retry only temporary failures. Set a small limit, wait longer each time, and add a random delay. Give each call a timeout.

Use an idempotency key for writes. It is a unique request ID that stops a repeated request from creating a second order. Too many retries can overload a weak service.

Q23. Should you split this app into microservices?

30-second answer: I start from team and scaling needs. Separate services help when parts need separate releases or very different capacity. They also add network failures and make shared data harder.

A well-organized single app is often a better start. Compare the costs in monolith vs microservices.

Q24. How do you handle an uncaught exception?

30-second answer: Log it, stop new work, and exit after a short cleanup. A process manager should start a fresh process. Do not continue as normal, because the program may hold bad data.

Expected problems, such as bad input, should be handled near the request. They should not become uncaught exceptions.

Interview note: When you tell a live-problem story, give the first sign, the cause, your fix and how you prevented it. Separate team work from your own.

Q25. How do you cache an API response?

30-second answer: I cache data that is read often and changes slowly. I choose a key, an expiry time and a way to remove old data after a change. I keep working if the cache is down.

Memory inside one Node process is fast, but other copies of the app cannot see it. Redis can share the cache between copies. Never put one user's private data under a key that another user can reach.

How to practise these answers

Build one small API with login, input checks, pages of results, file upload and tests. Then break it on purpose. Stop the database, send a huge body, and block the event loop for three seconds. Write down what you see and which log helped.

Next, add one database. If you pick MongoDB, revise the MongoDB interview questions. Explain why you chose it and which queries need an index.

For Node JS interview questions and answers for experienced roles, prepare one diagram of a real service and one live problem. Freshers can use the practice API as their project. This makes your Node JS interview questions and answers sound natural. The MERN stack program connects Node with React and MongoDB.

Before the interview, answer these three prompts without notes:

  1. A user clicks Pay twice. How do you prevent two orders?
  2. A partner API takes 30 seconds. What does your user see?
  3. One server restarts during an upload. What must the client do?

Each prompt joins several topics on this page: timeouts, idempotency, streams, errors and shutdown. A good answer names the failure first, then the fix, then how you would test it.

Frequently Asked Questions

Is Node.js a framework?
No. Node.js is a runtime that runs JavaScript outside the browser. Express is a framework that runs on Node.js.
Do I need to know Express for a Node.js interview?
Usually yes for web API roles. Know routing, middleware, error handling and input checks. If the job names another framework such as NestJS or Fastify, learn that too.
Which Node.js version should I mention in an interview?
Mention the version you use and say that production apps should run a supported LTS release. LTS means long-term support. Check the official Node.js release page for current dates.
Is TypeScript asked in Node.js interviews?
Often, because many teams use it. Learn basic types, interfaces, generics and why outside data still needs checks while the program runs.
What should a senior Node.js developer prepare?
Prepare one system design, one live problem you fixed, and one choice you would make differently. Be ready to explain how you measured the problem.
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 3 December 2026 LinkedIn
Chat with us