All posts

Top Node.js Interview Questions for Freshers

A developer preparing for a Node.js interview with notes and a laptop.

You have built three Express APIs, one with login and a MongoDB database. The interviewer glances at your resume and asks: "If Node is single-threaded, what happens when two hundred requests arrive at once?" You say "it's asynchronous", and the follow-up comes: "Asynchronous how? Who does the waiting?" Most Node.js interviews are won or lost on that second question, and the Node.js interview questions below are the ones that lead to it.

Backend interviewers assume you can write a route. What they probe is the runtime underneath it, because that is what breaks in production. Here are the 25 questions that come up most, grouped the way interviewers tend to move through them.

The short answer

Node.js is designed to handle multiple connections efficiently through its asynchronous, non-blocking architecture. When many requests arrive simultaneously, Node uses its event loop and callback mechanisms to manage them without getting blocked, allowing it to serve many clients concurrently.

The short answer

Key takeaways

  • Understanding the event loop is crucial for handling multiple requests in Node.js.
  • Asynchronous operations allow Node.js to manage high concurrency effectively.
  • Proper error handling is essential to maintain application stability and prevent crashes.

Understanding the Event Loop

The event loop is a core concept in Node.js that allows it to perform non-blocking I/O operations. It enables Node.js to handle multiple requests by offloading operations to the system's kernel or a thread pool, ensuring that the main thread remains free to process incoming requests.

By understanding how the event loop works, you can write more efficient Node.js applications that scale well under load. This knowledge is crucial for answering many interview questions related to performance and concurrency.

  • Middleware in Express must be registered in the correct order to function properly.
  • Security practices, such as input validation and rate limiting, are vital for protecting Node.js applications.

Best Practices for Error Handling

Effective error handling is vital in any Node.js application. Use the error-first callback pattern for traditional callbacks, and use promises and async/await for cleaner code. Always ensure that you handle both operational errors and programmer errors appropriately to maintain application stability.

In interviews, be prepared to discuss how you would implement error handling strategies in your applications, including the use of logging and monitoring tools to track errors in production.

Node.js developer interview questions cluster around five areas: the runtime (V8, libuv, the event loop and what blocks it), data handling (streams, backpressure, buffers), error handling (callbacks, promises, unhandled rejections), building APIs with Express (middleware order, REST design, authentication, config), and running Node in production (modules, npm, security, scaling, database pooling, logging and testing). For each one, say what actually happens inside Node, then why it matters for a real server. A memorised definition won't get you through the follow-up.

The runtime and the event loop

  1. What is Node.js?

Node.js is a JavaScript runtime, not a language or a framework. It combines Google's V8 engine, which compiles and runs your JavaScript, with libuv, a C library that provides the event loop, asynchronous I/O and a thread pool. On top, Node adds what a browser lacks: fs, net, http, process. It suits servers because I/O is non-blocking by default: while one request waits on a database, the same thread serves others.

  1. Node is single-threaded. How does it handle thousands of connections?

Your JavaScript runs on one thread, but the waiting happens elsewhere. Network I/O is handed to the operating system's async mechanisms (epoll on Linux, kqueue on macOS, IOCP on Windows), and some work goes to libuv's thread pool. When a result is ready, a callback is queued, and the event loop runs it once the call stack is empty. A server spends most of its time waiting on networks and disks, so one thread that handles only the quick JavaScript parts can serve many connections, as long as every callback finishes quickly.

  1. Walk me through the phases of the event loop.

Each turn of the loop goes through six phases in order:

  • timers: expired setTimeout and setInterval callbacks
  • pending callbacks: some deferred system errors
  • idle/prepare: internal use only
  • poll: fetches new I/O events and runs their callbacks, and waits here if nothing else is scheduled
  • check: setImmediate callbacks
  • close callbacks: for example a socket's close

Between callbacks, Node drains the process.nextTick queue, then the promise microtask queue. Since Node 11 this happens after each individual callback, not only between phases, which matches browser behaviour.

  1. What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?

process.nextTick runs as soon as the current operation finishes, before promise callbacks and before the loop moves on (in CommonJS; in an ES module's top-level code, promise callbacks can run first). setImmediate runs in the check phase. setTimeout(fn, 0) is really a minimum of 1ms and runs in the timers phase. From the main module, the order of setTimeout(0) and setImmediate isn't, because it depends on how long the process took to start. Inside an I/O callback, setImmediate always runs first, because the check phase comes straight after poll.

Likely follow-up

"Why is nextTick risky?" A recursive nextTick keeps refilling a queue that is drained before I/O, so it can starve the loop. Use setImmediate to defer work.

  1. What does blocking the event loop mean, and how do you avoid it?

It means a callback runs long enough that nothing else can: no new requests are accepted and no timers fire. Common causes are fs.readFileSync in a request handler, JSON.parse on a huge payload, CPU-heavy loops, and regular expressions that backtrack catastrophically on user input. Use async APIs on the request path, cap body sizes, split large jobs into chunks, and move real CPU work to worker threads or a job queue.

Likely follow-up

"How would you detect it?" Measure event loop delay with perf_hooks.monitorEventLoopDelay(), or profile with node --prof or the DevTools inspector.

  1. What is the libuv thread pool, and what uses it?

Some operations have no truly asynchronous OS interface, so libuv runs them on a pool of threads: most fs operations, dns.lookup, and CPU-heavy crypto (pbkdf2, scrypt) and zlib work. The default size is 4, set by UV_THREADPOOL_SIZE. Network sockets don't use it. With the default pool, five password hashes started at once means one of them waits.

  1. Worker threads, cluster or child processes: when do you use each?

Worker threads, stable since Node 12, run JavaScript in parallel inside one process and can share memory through SharedArrayBuffer, which makes them a fit for CPU-bound tasks like image processing. Cluster forks several Node processes that share one port, so request handling uses every core. Child processes (spawn, exec, fork) run a separate program, such as a shell command or a Python script.

Streams, buffers and errors

  1. What are streams, and why use them?

A stream processes data piece by piece instead of loading it all into memory. There are four types: Readable, Writable, Duplex (both, like a TCP socket) and Transform (a Duplex that changes the data, like gzip). Serving a 2GB file with readFile holds 2GB in memory per request. fs.createReadStream(path).pipe(res) holds a small buffer, and the client gets the first bytes immediately.

  1. What is backpressure?

Backpressure is what happens when the consumer is slower than the producer, for example reading from a fast disk and writing to a slow client. If you ignore it, data piles up in memory. A writable stream signals it by returning false from write(), and you stop writing until the drain event fires. pipe() and stream.pipeline() handle this for you. Use pipeline (the promise version is in stream/promises): if any stream fails, it destroys all of them and reports the error, which pipe does not.

  1. What is a Buffer?

A Buffer is a fixed-length chunk of raw binary memory, allocated outside the V8 heap. It is a subclass of Uint8Array. Node needs it because sockets, files and crypto output are bytes, not strings. Create one with Buffer.from() or Buffer.alloc(); the old new Buffer() constructor is deprecated. Buffer.allocUnsafe() is faster but may contain old memory, so overwrite it fully before exposing it.

  1. How do you handle errors with callbacks, promises and async/await?

Callbacks use the error-first convention (err, result), so check err first. A try/catch around a callback API does nothing, because the error arrives later on a different stack. Promises take.catch(), and async/await takes try/catch around the await. The classic bug is a missing await, which lets the rejection escape the try. Also separate operational errors you can handle (a timeout, bad input) from programmer errors (an undefined access), which should crash the process so you fix them.

  1. What happens when a promise rejection is unhandled?

Since Node 15, an unhandled rejection crashes the process by default, the same as an uncaught exception. Before that, Node only printed a warning, so a server could run for weeks silently dropping errors. You can listen on process.on('unhandledRejection') and process.on('uncaughtException'), but only to log and exit. After one of these errors the process may be in an unknown state, so let a process manager restart it.

Express and API design

  1. How does Express middleware work, and why does order matter?

Middleware is a function (req, res, next), and Express runs middleware in the order you register it. Each one either ends the response or calls next(). Order matters because each step depends on the earlier ones: express.json() must run before a handler reads req.body, authentication must run before protected routes, and a rate limiter registered after a route never runs for it. Middleware that neither responds nor calls next() leaves the request hanging until it times out.

  1. How do you handle errors in Express?

Express recognises error middleware by its four arguments, (err, req, res, next). You register it after all routes and reach it with next(err). In Express 4, a rejected promise in an async handler wasn't caught, so you needed a wrapper or express-async-errors. Express 5, released in late 2024, forwards rejected promises to the error middleware automatically.

  1. What makes a good REST API design?

Resources are nouns in the URL (/users/42/orders), and HTTP methods are the verbs. Use correct status codes: 201 created, 400 invalid input, 401 not authenticated, 403 not allowed, 404 not found, 409 conflict. GET, PUT and DELETE should be idempotent; POST isn't assumed to be. Paginate lists, and version the API (/api/v1) so you can change it without breaking clients.

Likely follow-up

"How do you make a payment endpoint safe to retry?" Accept an idempotency key from the client, and return the stored result when the same key arrives again.

  1. JWT or sessions for authentication?

With sessions, the server stores the session data (often in Redis), and the client holds only an ID in a cookie. Revoking access means deleting the session. A JWT carries its signed claims itself, so any server can verify it without a lookup, which suits systems with several services. The cost is revocation: a stolen token stays valid until it expires. The usual answer is short-lived access tokens plus a revocable refresh token. An httpOnly cookie keeps the token away from JavaScript, but then you need CSRF protection.

  1. How do you manage configuration and environment variables?

Anything that changes between environments (database URLs, API keys, ports) comes from environment variables and never from committed code. Read process.env once in a config module and validate it at startup, so a missing key fails the boot instead of the first request that needs it. Node 20.6 added a built-in --env-file flag, so local development no longer needs dotenv. Keep.env out of version control and commit a.env.example.

Modules and tooling

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

CommonJS uses require and module.exports and loads modules synchronously at runtime, so you can call require inside an if. ES modules use import and export and can be analysed statically, which enables tree-shaking. They support top-level await and have no __dirname (use import.meta.dirname or import.meta.url). A file is an ES module if it ends in.mjs or the nearest package.json has "type": "module". ES modules can import CommonJS. Calling require() on an ES module works without a flag since Node 22.12 and 20.19, as long as the module has no top-level await.

  1. What is the difference between package.json and package-lock.json?

package.json lists dependency ranges: ^4.18.2 allows any 4.x version from 4.18.2 up, and ~4.18.2 allows only 4.18.x patches. package-lock.json records the exact version of every installed package, including nested ones, so every machine gets the same tree. Commit it. In CI, use npm ci: it installs exactly what the lockfile says, removes node_modules first, and fails if the lockfile and package.json disagree.

  1. What is the difference between npm and npx?

npm manages packages: installing, updating and running package.json scripts. npx runs a package's executable. It uses the local copy if one is installed and otherwise downloads the package temporarily, so npx create-vite needs no global install.

Production: security, scaling, data, logging, tests

  1. What are the security basics for a Node API?

Start with injection. For SQL, use parameterised queries or an ORM, never string concatenation. For MongoDB, watch for operator injection: a body like {"password": {"$ne": null}} passed straight into a query can bypass a login, so validate types with Zod or Joi. After that, rate-limit login and expensive routes, hash passwords with bcrypt, scrypt or argon2, set security headers with helmet, limit body size, and run npm audit, since most of the code you ship is dependencies.

Likely follow-up

"Does an in-memory rate limiter work across four servers?" No. Each server keeps its own count, so use a shared store like Redis.

  1. How do you scale a Node application?

First use every core on one machine, with the cluster module or PM2 in cluster mode, which also restarts crashed processes. Then scale horizontally behind a load balancer. That only works if the app is stateless, with no sessions, uploads or caches in process memory, because the next request may reach a different instance. Move that state to Redis, a database or object storage.

  1. How do you connect to a database, and what is connection pooling?

Opening a connection is expensive: a TCP handshake, often TLS, then authentication. A pool keeps connections open and lends them to queries. Create the pool once at startup, never per request. Size it carefully. Too small and requests queue; too large and you exhaust the database's connection limit, since the real total is the number of instances multiplied by the pool size. Release connections on error paths too, or the pool slowly runs dry. For the database side, see our SQL interview questions and answers.

  1. How should you log in a Node application?

Use structured JSON logs from a library such as Pino or Winston instead of console.log, so you can filter logs by field. Set log levels per environment, attach a request ID to every line so you can follow one request across services, and never log passwords, tokens or card details.

  1. How do you test a Node.js API?

Preparing for Node.js Interviews

To excel in Node.js interviews, practice answering common questions and understand the underlying concepts. Mock interviews can help simulate the experience, allowing you to articulate your thoughts clearly. Focus on explaining your reasoning and demonstrating your knowledge of Node.js features and best practices.

Additionally, reviewing related topics such as JavaScript fundamentals and asynchronous programming will strengthen your overall interview performance.

Unit-test business logic with its dependencies mocked. Then write integration tests that send real HTTP requests against a test database; Supertest is the usual tool. Node 20 made the built-in node:test runner stable, though Jest and Vitest are still common. Export the Express app separately from the listen() call, so tests can import it without opening a port.

How to practise these

Knowing these answers on paper won't carry you through a real interview, because the questions chain. Question 2 leads straight to question 3, and then to "where does a setImmediate inside this readFile callback run?" That follow-up shows whether you understood the answer or memorised it, as we explain in why knowing the answer isn't enough. When you hit a question you can't answer, read how to handle a question you don't know. Revise the language underneath too. Closures, promises and this come up in every Node round, and our JavaScript interview questions cover them.

Then practise out loud. On 99interview, Sia, our AI interviewer, asks one question at a time and follows up on what you actually said. Pick Node.js as your stack, choose a difficulty (Beginner, Standard or Senior) and a round length, and you get a scored written breakdown when you finish. The backend practice track is the place to start. If you want a human interviewer, book a live 40-minute Zoom interview with a working engineer. It's scored on technical depth, problem solving, communication, behaviour and code quality, and you get written feedback.

If you're still building the basics, the fresher preparation hub shows what to cover first.

The official Node.js docs go deeper on everything above.

You can rehearse this out loud in Node.js interview practice.

The official Node.js documentation is the reference for the event loop, streams and core modules.

See how others prepared in our candidate stories, and who has been hired on the display board.