Web Development

Top 50 Node.js Interview Questions and Answers (2026): Complete Guide for Beginners and Experienced Developers

Node.js is one of the most popular technologies for backend development. It allows developers to build REST APIs, real-time applications, microservices, and…

D
DevByteTechnical Author
Published
38 min read18 views
Top 50 Node.js Interview Questions and Answers (2026): Complete Guide for Beginners and Experienced Developers

Node.js is one of the most popular technologies for backend development. It allows developers to build REST APIs, real-time applications, microservices, and scalable web applications using JavaScript.

If you are preparing for a Node.js developer interview, you should understand more than just definitions. Interviewers often ask how things work internally, why you would choose one approach over another, and how you would solve real-world backend problems.

In this guide, we cover 50 important Node.js interview questions, from fundamentals to advanced backend development.

Every question includes two parts:

  • Part 1 — Interview Answer: A concise answer you can confidently explain during an interview.

  • Part 2 — Detailed Explanation: A beginner-friendly explanation with examples and practical context.

Whether you are a fresher or an experienced backend developer, this guide will help you prepare for Node.js and Express.js interviews.

Table of Contents

  1. Node.js Fundamentals

  2. Event Loop and Asynchronous Programming

  3. Express.js and REST APIs

  4. Databases and Data Handling

  5. Security, Performance, and Scalability

1. Node.js Fundamentals

1. What is Node.js, and why is it used?

Part 1 — Interview Answer

Node.js is an open-source, cross-platform JavaScript runtime environment built on Chrome's V8 JavaScript engine. It allows developers to execute JavaScript outside the browser.

Node.js is commonly used for REST APIs, real-time applications, microservices, streaming applications, and backend services. Its non-blocking I/O model makes it suitable for applications that handle many concurrent connections.

Part 2 — Detailed Explanation

Normally, JavaScript runs inside a browser to handle things such as button clicks, form validation, and DOM manipulation.

Node.js allows JavaScript to run on a server. This means developers can use JavaScript for both frontend and backend development.

For example, you can create an HTTP server using Node.js:

const http = require("node:http");

const server = http.createServer((req, res) => {
  res.writeHead(200, {
    "Content-Type": "text/plain",
  });

  res.end("Hello from Node.js!");
});

server.listen(3000, () => {
  console.log("Server running on port 3000");
});

Run this file and visit http://localhost:3000 in your browser.

You will see the response from your Node.js server.

When should you use Node.js?

  • Building REST APIs and backend services.

  • Developing chat applications using WebSockets.

  • Building applications that perform many network or database operations.

  • Creating microservices and real-time notification systems.

Node.js is not automatically the best choice for every workload. CPU-intensive tasks may need worker threads, separate services, or another runtime better suited to the task.

2. How does Node.js differ from browser JavaScript?

Part 1 — Interview Answer

JavaScript is the programming language, while Node.js is a runtime that executes JavaScript outside the browser.

Browser JavaScript provides browser-specific APIs such as the DOM, window, and document. Node.js provides server-side APIs such as process, filesystem access, and networking.

Both environments support core JavaScript features, but their available APIs and security boundaries are different.

Part 2 — Detailed Explanation

Consider this browser code:

document.querySelector("button").addEventListener(
  "click",
  () => {
    console.log("Button clicked");
  }
);

It works in a browser because the browser provides document.

The same code will fail in a typical Node.js environment because Node.js does not provide the browser DOM.

In Node.js, you can work with files:

const fs = require("node:fs");

const content = fs.readFileSync(
  "message.txt",
  "utf8"
);

console.log(content);

Node.js has access to server-side resources, so you must be careful about file permissions, user input, and sensitive data.

Key difference: Browser JavaScript primarily interacts with web pages and browser APIs, whereas Node.js JavaScript can interact with server-side resources.

3. What is the V8 engine?

Part 1 — Interview Answer

V8 is an open-source JavaScript engine developed by Google. It compiles and executes JavaScript and is used by Chrome and Node.js.

V8 uses techniques such as just-in-time compilation and optimization to execute JavaScript efficiently. Node.js combines V8 with additional runtime APIs and facilities for networking, filesystem operations, and asynchronous I/O.

Part 2 — Detailed Explanation

When you write JavaScript, the computer needs to execute it. V8 handles the JavaScript execution part.

For example:

const a = 10;
const b = 20;

console.log(a + b);

V8 parses and executes this JavaScript, applying optimizations where appropriate.

However, V8 alone is not the entire Node.js runtime. Node.js also provides modules and APIs, and uses components such as libuv for its event loop and asynchronous I/O coordination.

A simple way to remember it:

  • V8: Executes JavaScript.

  • Node.js: Provides the runtime environment and server-side APIs.

  • libuv: Helps coordinate the event loop and many asynchronous I/O operations.

4. Is Node.js single-threaded?

Part 1 — Interview Answer

Node.js normally executes JavaScript callbacks on a single main thread per isolate, but that does not mean the entire runtime is single-threaded.

It can handle asynchronous I/O through operating-system facilities and libuv's thread pool. Node.js also supports worker threads for CPU-intensive JavaScript tasks and clustering for running multiple processes.

Part 2 — Detailed Explanation

Consider this code:

console.log("Start");

setTimeout(() => {
  console.log("Timer finished");
}, 1000);

console.log("End");

The output is:

Start
End
Timer finished

Node.js does not need to stop executing JavaScript while waiting for the timer.

This is one reason Node.js works well for applications that spend a lot of time waiting for databases, APIs, or other I/O operations.

However, a long-running calculation can block the main JavaScript thread:

function calculate() {
  let result = 0;

  for (let i = 0; i < 1_000_000_000; i++) {
    result += i;
  }

  return result;
}

While this calculation is running, other JavaScript callbacks on that thread cannot execute.

For CPU-intensive workloads, consider worker threads, child processes, or a separate processing service.

5. What are Node.js global objects?

Part 1 — Interview Answer

Global objects and values are available without explicitly importing them in the usual way. Examples include globalThis, process, console, and timer functions.

Node.js also provides module-related values such as __dirname and __filename in CommonJS modules. These are not available in the same form in native ES modules.

Part 2 — Detailed Explanation

For example:

console.log(process.version);
console.log(process.platform);

setTimeout(() => {
  console.log("Executed after one second");
}, 1000);

Here:

  • process.version shows the Node.js version.

  • process.platform identifies the operating-system platform.

  • setTimeout() schedules a callback to run after a delay.

In CommonJS, you can also use:

console.log(__dirname);
console.log(__filename);

These values show the current module's directory and filename.

In ES modules, you can derive similar information from import.meta.url.

Avoid adding unnecessary variables to the global scope because global state can make an application harder to test and maintain.

6. What is the purpose of package.json?

Part 1 — Interview Answer

package.json is the main configuration and metadata file for a Node.js project. It defines information such as the project name, version, scripts, dependencies, and package requirements.

It allows developers and package managers to install dependencies and run standard project commands consistently.

Part 2 — Detailed Explanation

Example:

{
  "name": "my-api",
  "version": "1.0.0",
  "description": "A simple Node.js API",
  "scripts": {
    "start": "node server.js",
    "dev": "node --watch server.js"
  },
  "dependencies": {
    "express": "^5.0.0"
  }
}

You can run a script with:

npm start

Or:

npm run dev

The scripts section helps standardize commands used by developers and deployment pipelines.

The dependencies section lists packages needed by the application at runtime. A lockfile, such as package-lock.json, records the resolved dependency versions to improve reproducibility.

7. What is the difference between dependencies and devDependencies?

Part 1 — Interview Answer

dependencies contains packages required to run the application, while devDependencies contains packages primarily needed during development, testing, building, or linting.

For example, Express is usually a runtime dependency, whereas ESLint and many testing tools are development dependencies.

Part 2 — Detailed Explanation

Install a runtime dependency:

npm install express

Install a development dependency:

npm install --save-dev eslint

Your package.json might contain:

{
  "dependencies": {
    "express": "^5.0.0"
  },
  "devDependencies": {
    "eslint": "^9.0.0"
  }
}

The distinction matters when deploying applications. A production installation may omit development dependencies, so packages needed to run the application must be classified correctly.

Some build tools are dev dependencies even when the final production application depends on the output they generate.

8. What is the difference between CommonJS and ES Modules?

Part 1 — Interview Answer

CommonJS and ES Modules are two module systems supported by Node.js.

CommonJS uses require() and module.exports, whereas ES Modules use import and export. ES Modules are the standardized JavaScript module system and support static imports and exports.

Part 2 — Detailed Explanation

CommonJS example:

// math.js
function add(a, b) {
  return a + b;
}

module.exports = { add };

Import it:

const { add } = require("./math.js");

console.log(add(2, 3));

ES Modules example:

// math.mjs
export function add(a, b) {
  return a + b;
}

Import it:

import { add } from "./math.mjs";

console.log(add(2, 3));

A project can use .mjs files for ES Modules or configure .js files with "type": "module" in package.json.

Choose a module system consistently and understand the configuration of your project.

9. What is the process object in Node.js?

Part 1 — Interview Answer

The process object provides information about and control over the current Node.js process. It can access environment variables, command-line arguments, process information, and process lifecycle events.

It is commonly used for configuration, logging, graceful shutdown, and command-line applications.

Part 2 — Detailed Explanation

Example:

console.log(process.version);
console.log(process.pid);
console.log(process.argv);

To access an environment variable:

const port = process.env.PORT || 3000;

console.log(`Port: ${port}`);

process.env.PORT reads the configured port, while 3000 is a fallback.

You can also handle termination signals:

process.on("SIGTERM", () => {
  console.log("Shutdown signal received");
});

In a real server, the handler should close the HTTP server and other resources rather than merely logging a message.

10. What are environment variables?

Part 1 — Interview Answer

Environment variables are configuration values supplied to a running application through its environment. They are commonly used for ports, database URLs, API keys, and feature settings.

They allow the same application code to run in development, testing, and production with different configurations.

Part 2 — Detailed Explanation

For example, your local .env file might contain:

PORT=5000
DATABASE_URL=your_database_url

You can read the values in Node.js:

const port = process.env.PORT || 3000;

console.log(port);

If you use the dotenv package, load the file first:

require("dotenv").config();

Environment variables are not automatically secret just because they are environment variables. Avoid logging secrets, committing .env files, or exposing private credentials to frontend applications.

In production, use your hosting platform's environment configuration or a secrets manager.

2. Event Loop and Asynchronous Programming

11. How does the Node.js event loop work?

Part 1 — Interview Answer

The event loop coordinates the execution of JavaScript callbacks and asynchronous operations. It allows Node.js to continue processing JavaScript while many I/O operations are waiting to complete.

Node.js executes JavaScript on the current thread, while asynchronous work is coordinated through operating-system facilities, libuv, and other runtime mechanisms. When operations complete, their callbacks can be scheduled for execution.

Part 2 — Detailed Explanation

Consider:

console.log("First");

setTimeout(() => {
  console.log("Second");
}, 0);

console.log("Third");

The output is typically:

First
Third
Second

Why?

  1. Node.js executes console.log("First").

  2. It registers the timer.

  3. It continues executing the current JavaScript code.

  4. It prints Third.

  5. The timer callback executes when the runtime reaches the appropriate opportunity.

A zero-millisecond timer does not mean the callback runs immediately.

The event loop also has phases for timers, I/O callbacks, polling, and other work. Promise callbacks and process.nextTick() have their own scheduling behavior relative to this loop.

12. What is non-blocking I/O?

Part 1 — Interview Answer

Non-blocking I/O allows Node.js to initiate an input/output operation and continue executing other work instead of waiting synchronously for the operation to finish.

It is useful for applications that perform many network requests, database operations, or filesystem tasks.

Part 2 — Detailed Explanation

Blocking example:

const fs = require("node:fs");

const data = fs.readFileSync("data.txt", "utf8");

console.log(data);
console.log("Finished reading");

The synchronous file read blocks JavaScript until the operation completes.

Non-blocking example:

const fs = require("node:fs");

fs.readFile("data.txt", "utf8", (error, data) => {
  if (error) {
    console.error(error);
    return;
  }

  console.log(data);
});

console.log("Other work can continue");

The second example can print "Other work can continue" before the file contents are printed.

Non-blocking I/O improves concurrency, but it does not make every operation faster. CPU-heavy JavaScript can still block the event loop.

13. What is the difference between callbacks, Promises, and async/await?

Part 1 — Interview Answer

Callbacks are functions passed to another function for execution later. Promises represent the eventual success or failure of an asynchronous operation. async/await provides a cleaner syntax for working with Promises.

All three can be used to manage asynchronous work, but Promises and async/await often make complex asynchronous flows easier to read and maintain.

Part 2 — Detailed Explanation

Callback example:

setTimeout(() => {
  console.log("Task completed");
}, 1000);

Promise example:

const task = new Promise((resolve) => {
  resolve("Task completed");
});

task.then((result) => {
  console.log(result);
});

Async/await example:

async function runTask() {
  const result = await Promise.resolve("Task completed");
  console.log(result);
}

runTask();

The important point is that await waits for a Promise's result within the asynchronous function. It does not block the entire Node.js process while the Promise is pending.

For error handling, use .catch() with Promise chains or try/catch with async/await.

14. What is callback hell?

Part 1 — Interview Answer

Callback hell occurs when multiple nested callbacks make asynchronous code difficult to read, debug, and maintain.

It can be reduced by using Promises, async/await, named functions, and appropriate error-handling patterns.

Part 2 — Detailed Explanation

Imagine fetching a user, then their orders, and then the details of a particular order.

Nested callbacks can look like this:

getUser((error, user) => {
  if (error) return handleError(error);

  getOrders(user.id, (error, orders) => {
    if (error) return handleError(error);

    getOrderDetails(orders[0].id, (error, details) => {
      if (error) return handleError(error);

      console.log(details);
    });
  });
});

With Promise-based functions, the same flow can be easier to follow:

async function getUserOrderDetails() {
  try {
    const user = await getUser();
    const orders = await getOrders(user.id);
    const details = await getOrderDetails(orders[0].id);

    console.log(details);
  } catch (error) {
    console.error("Unable to retrieve order details");
  }
}

This example assumes the functions return Promises.

15. What is the difference between Promise.all() and Promise.allSettled()?

Part 1 — Interview Answer

Promise.all() fulfills when every input Promise fulfills, but rejects as soon as one input Promise rejects. Promise.allSettled() waits for every input Promise to settle and returns the outcome of each operation.

Use Promise.all() when all results are required for success. Use Promise.allSettled() when you want to inspect successful and failed operations individually.

Part 2 — Detailed Explanation

Example using Promise.all():

const results = await Promise.all([
  fetchUser(),
  fetchProducts(),
  fetchOrders()
]);

If one Promise rejects, the combined Promise rejects. The other operations are not automatically cancelled.

Example using Promise.allSettled():

const results = await Promise.allSettled([
  fetchUser(),
  fetchProducts(),
  fetchOrders()
]);

for (const result of results) {
  if (result.status === "fulfilled") {
    console.log("Success:", result.value);
  } else {
    console.log("Failed:", result.reason);
  }
}

The second approach is useful for independent operations where partial success is acceptable.

16. What is the difference between setTimeout() and setImmediate()?

Part 1 — Interview Answer

setTimeout() schedules a callback after a specified minimum delay, while setImmediate() schedules a callback to execute in the event loop's check phase.

Their execution order can depend on the context in which they are scheduled. At the top level, you should not assume a universal ordering between setTimeout(fn, 0) and setImmediate(fn).

Part 2 — Detailed Explanation

Example:

setTimeout(() => {
  console.log("Timeout");
}, 0);

setImmediate(() => {
  console.log("Immediate");
});

Depending on the runtime and scheduling context, either callback may execute first.

Inside an I/O callback, setImmediate() generally runs before a newly scheduled zero-delay timer:

const fs = require("node:fs");

fs.readFile(__filename, () => {
  setTimeout(() => console.log("Timeout"), 0);

  setImmediate(() => console.log("Immediate"));
});

This is because setImmediate() callbacks are handled in the event loop's check phase after polling for I/O.

17. What is process.nextTick()?

Part 1 — Interview Answer

process.nextTick() schedules a callback to run after the current JavaScript operation completes but before the event loop continues to its next phase.

It is different from setTimeout() and setImmediate(). Excessive recursive use of process.nextTick() can prevent the event loop from progressing.

Part 2 — Detailed Explanation

Example:

console.log("Start");

process.nextTick(() => {
  console.log("Next tick");
});

console.log("End");

Output:

Start
End
Next tick

The callback does not interrupt the current synchronous code. It runs after the current operation finishes.

Node.js also schedules Promise microtasks, such as .then() callbacks. The precise ordering between process.nextTick() and Promise microtasks can depend on the execution context, so avoid relying on simplified scheduling rules for complicated flows.

18. What are microtasks and macrotasks?

Part 1 — Interview Answer

Microtasks are high-priority queued callbacks that run at defined points after the current JavaScript execution completes. Promise reactions are a common example.

Tasks commonly called macrotasks include timer callbacks and many event-loop callbacks. Node.js also has its own event-loop phases and process.nextTick() queue, so browser scheduling terminology does not map perfectly onto every Node.js detail.

Part 2 — Detailed Explanation

Consider:

console.log("Start");

setTimeout(() => {
  console.log("Timer");
}, 0);

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("End");

A typical output is:

Start
End
Promise
Timer

The synchronous code runs first. The Promise reaction then executes before the timer callback in this example.

This knowledge helps you understand asynchronous output, but in real Node.js applications you should also consider I/O callbacks, process.nextTick(), and the context in which callbacks are scheduled.

19. How can CPU-intensive tasks block Node.js?

Part 1 — Interview Answer

CPU-intensive synchronous operations block the JavaScript thread, preventing the event loop from executing other JavaScript callbacks on that thread.

To handle expensive calculations, developers can use worker threads, child processes, background job systems, or separate services.

Part 2 — Detailed Explanation

Suppose an API endpoint performs a large calculation:

app.get("/calculate", (req, res) => {
  let result = 0;

  for (let i = 0; i < 1_000_000_000; i++) {
    result += i;
  }

  res.json({ result });
});

While the loop runs, other requests handled by the same JavaScript thread may have to wait.

Possible solutions include:

  • Move CPU-heavy JavaScript into a worker thread.

  • Send background work to a job queue.

  • Split work into smaller chunks when appropriate.

  • Use a separate service for computationally intensive tasks.

Simply making an API asynchronous does not make its CPU-heavy calculations non-blocking.

20. What is the difference between worker threads and clustering?

Part 1 — Interview Answer

Worker threads allow multiple JavaScript threads within a Node.js process and are particularly useful for CPU-intensive tasks.

The cluster module creates multiple Node.js processes that can share server ports and distribute incoming connections. It can improve the use of multiple CPU cores for server workloads.

Part 2 — Detailed Explanation

Use worker threads when a task requires significant computation, such as processing a large dataset or performing complex calculations.

Use clustering when you want multiple Node.js server processes to handle incoming requests.

A simplified comparison:

Feature

Worker Threads

Cluster

Execution

Multiple threads

Multiple processes

Memory

Can share memory through supported mechanisms

Separate process memory

Common use

CPU-intensive calculations

Scaling server request handling

Failure isolation

Same process

Stronger process isolation

Both approaches add complexity. The right choice depends on the workload, deployment environment, and how tasks communicate.

3. Express.js and REST APIs

21. What is Express.js?

Part 1 — Interview Answer

Express.js is a web framework for Node.js that simplifies building HTTP servers and REST APIs. It provides routing, middleware support, request and response utilities, and integration with other packages.

It allows developers to build backend applications without manually implementing every HTTP-handling detail.

Part 2 — Detailed Explanation

Install Express:

npm install express

Create a basic server:

const express = require("express");

const app = express();

app.get("/", (req, res) => {
  res.send("Hello from Express!");
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

When a client sends a GET request to /, Express matches the route and sends a response.

Express is commonly used to create REST APIs, authentication endpoints, and backend services.

22. How does middleware work in Express.js?

Part 1 — Interview Answer

Middleware is a function that can access the request object, response object, and next() function. It can execute code, modify the request or response, end the request-response cycle, or pass control to subsequent middleware.

Middleware is commonly used for authentication, logging, validation, parsing request bodies, and error handling.

Part 2 — Detailed Explanation

Example:

const express = require("express");

const app = express();

app.use(express.json());

app.use((req, res, next) => {
  console.log(req.method, req.url);
  next();
});

app.get("/", (req, res) => {
  res.json({ message: "Hello" });
});

app.listen(3000);

Here:

  1. express.json() parses supported JSON request bodies.

  2. The logging middleware prints the HTTP method and URL.

  3. next() passes control to the next matching middleware or route.

If middleware neither sends a response nor calls next() or an appropriate alternative, the request may remain unfinished.

23. What is the difference between application-level and router-level middleware?

Part 1 — Interview Answer

Application-level middleware is registered on the main Express application using methods such as app.use(). Router-level middleware is attached to an Express router using router.use() or route-specific handlers.

Application-level middleware is useful for cross-application behavior, while router-level middleware is useful for functionality scoped to a particular group of routes.

Part 2 — Detailed Explanation

Application-level middleware:

app.use(express.json());

app.use((req, res, next) => {
  console.log("Request received");
  next();
});

Router-level middleware:

const express = require("express");

const router = express.Router();

router.use((req, res, next) => {
  console.log("User routes accessed");
  next();
});

router.get("/profile", (req, res) => {
  res.json({ message: "User profile" });
});

app.use("/users", router);

The router middleware applies to routes handled by that router. This helps keep larger applications organized into modules.

24. What does next() do in Express.js?

Part 1 — Interview Answer

next() passes control to the next matching middleware or route handler in the Express request-processing chain.

Calling next(error) passes an error to error-handling middleware. Calling next("route") in supported route-handler contexts skips the remaining handlers for the current route.

Part 2 — Detailed Explanation

Example:

app.use((req, res, next) => {
  console.log("Middleware executed");
  next();
});

app.get("/", (req, res) => {
  res.send("Response sent");
});

The first middleware logs the request and calls next(), allowing the route handler to run.

You can also pass errors:

app.get("/example", (req, res, next) => {
  const error = new Error("Something went wrong");
  next(error);
});

The error can then be handled centrally.

Do not call next() after sending a response unless you deliberately intend to pass control onward; doing so can cause duplicate-response errors.

25. How do you handle errors centrally in Express.js?

Part 1 — Interview Answer

I handle errors using centralized error-handling middleware with four parameters: err, req, res, and next. Route handlers pass errors to this middleware instead of duplicating response logic throughout the application.

The handler logs appropriate diagnostic details, chooses a suitable HTTP status code, and returns a safe error response to the client.

Part 2 — Detailed Explanation

Example:

app.get("/user", (req, res, next) => {
  try {
    throw new Error("User not found");
  } catch (error) {
    next(error);
  }
});

app.use((err, req, res, next) => {
  console.error(err);

  if (res.headersSent) {
    return next(err);
  }

  res.status(err.status || 500).json({
    message:
      err.status && err.status < 500
        ? err.message
        : "Internal server error",
  });
});

In a real application, distinguish expected errors, such as validation failures, from unexpected server errors.

Avoid returning stack traces, database details, credentials, or internal implementation information to clients in production.

Express 5 automatically forwards rejected Promises returned by route handlers to error-handling middleware. In Express 4, asynchronous errors generally require explicit forwarding or a compatible wrapper.

26. How do you validate incoming requests?

Part 1 — Interview Answer

I validate request bodies, query parameters, and route parameters using a schema-validation library such as Joi or Zod. I check required fields, data types, allowed values, and business rules before processing the request.

I also reject invalid input with a suitable 4xx response and use parameterized database operations to prevent injection attacks.

Part 2 — Detailed Explanation

For example, a registration endpoint might require a valid email address and a sufficiently strong password.

Using Joi:

const Joi = require("joi");

const userSchema = Joi.object({
  name: Joi.string().min(2).max(100).required(),
  email: Joi.string().email().required(),
  age: Joi.number().integer().min(18).optional(),
});

app.post("/users", (req, res) => {
  const { error, value } = userSchema.validate(req.body);

  if (error) {
    return res.status(400).json({
      message: error.details[0].message,
    });
  }

  // Use validated data for the next step.
  res.status(201).json({
    message: "User data validated",
    user: value,
  });
});

The example demonstrates validation, not actual user creation.

Validation should be performed on the server even if the frontend already validates the same fields. Client-side validation improves user experience, but it cannot be trusted as a security boundary.

27. What is the difference between PUT and PATCH?

Part 1 — Interview Answer

PUT is generally used to replace the representation of a resource, while PATCH is used to apply partial modifications.

PUT is defined as an idempotent HTTP method. PATCH is not inherently idempotent, although a particular PATCH operation can be designed to be idempotent.

Part 2 — Detailed Explanation

Suppose a user resource looks like this:

{
  "name": "Rahul",
  "email": "rahul@example.com",
  "city": "Jaipur"
}

A PUT request might replace the resource representation:

PUT /users/123
{
  "name": "Rahul",
  "email": "rahul@example.com",
  "city": "Delhi"
}

A PATCH request might change only the city:

PATCH /users/123
{
  "city": "Delhi"
}

The exact behavior depends on the API contract. For PUT, define how omitted fields are treated rather than assuming every implementation behaves identically.

28. How do you implement pagination in a REST API?

Part 1 — Interview Answer

Pagination divides a large result set into smaller responses. Common approaches include limit-offset pagination and cursor-based pagination.

For smaller datasets, limit-offset pagination can be straightforward. For large or frequently changing datasets, cursor-based pagination can provide more consistent performance.

Part 2 — Detailed Explanation

A basic offset-based example:

app.get("/products", async (req, res, next) => {
  try {
    const page = Math.max(
      1,
      Number.parseInt(req.query.page, 10) || 1
    );

    const limit = Math.min(
      100,
      Math.max(
        1,
        Number.parseInt(req.query.limit, 10) || 10
      )
    );

    const skip = (page - 1) * limit;

    const products = await Product.find()
      .sort({ createdAt: -1, _id: -1 })
      .skip(skip)
      .limit(limit);

    res.json({
      page,
      limit,
      data: products,
    });
  } catch (error) {
    next(error);
  }
});

This example assumes a Mongoose model named Product.

Pagination should also validate numeric inputs and use deterministic sorting. Very large offsets can become expensive, which is one reason cursor-based pagination is useful for large collections.

29. How do you handle CORS in Node.js?

Part 1 — Interview Answer

CORS stands for Cross-Origin Resource Sharing. It is a browser security mechanism that controls whether a webpage can access resources from a different origin.

In Express, I configure CORS using the cors middleware and explicitly allow the trusted frontend origins and HTTP methods required by the application.

Part 2 — Detailed Explanation

Install the package:

npm install cors

Configure it:

const cors = require("cors");

app.use(cors({
  origin: [
    "http://localhost:3000",
    "https://example.com",
  ],
  methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
}));

Replace the example domains with your actual frontend origins.

An origin consists of a scheme, hostname, and port. For example, http://localhost:3000 and http://localhost:5173 are different origins.

For credentialed requests, configure credentials: true where needed and use specific allowed origins rather than *.

CORS is not a replacement for authentication or authorization. Non-browser clients are not constrained by browser CORS enforcement.

30. How would you implement API rate limiting?

Part 1 — Interview Answer

Rate limiting restricts the number of requests a client can make within a defined period. It protects APIs against excessive usage, brute-force attempts, and some forms of abuse.

I would use a rate-limiting middleware, configure limits according to the endpoint, and use a shared store such as Redis when the application runs across multiple server instances.

Part 2 — Detailed Explanation

Install Express rate limiting:

npm install express-rate-limit

Configure a basic limiter:

const rateLimit = require("express-rate-limit");

const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  limit: 100,
  standardHeaders: "draft-8",
  legacyHeaders: false,
});

app.use("/api", apiLimiter);

This example allows up to 100 requests per client key during a 15-minute window, subject to the middleware's configured behavior.

In production:

  • Use stricter limits for login, password reset, and OTP endpoints.

  • Configure proxy trust carefully when running behind a reverse proxy.

  • Consider Redis or another shared store across multiple instances.

  • Monitor rejected requests and adjust limits to legitimate usage patterns.

4. Databases and Data Handling

31. What is the difference between SQL and NoSQL?

Part 1 — Interview Answer

SQL databases generally organize data into relational tables and support structured querying and relational constraints. NoSQL is a broad category that includes document, key-value, wide-column, and graph databases.

I choose a database based on the data model, consistency requirements, query patterns, relationships, transaction needs, and operational requirements rather than assuming one category is always faster.

Part 2 — Detailed Explanation

SQL examples include PostgreSQL and MySQL. A table might contain users with columns such as id, name, and email.

NoSQL examples include MongoDB and Redis. MongoDB stores documents, while Redis provides data structures such as strings, hashes, sets, and sorted sets.

Choose a relational database when you need strong relational constraints, complex joins, or transactions across related records.

Choose a document database when its document model fits the application and your access patterns benefit from storing related fields together.

Both SQL and NoSQL databases can support transactions, indexes, and scalable applications. The right choice depends on your actual requirements.

32. What is database connection pooling?

Part 1 — Interview Answer

Connection pooling maintains a reusable set of database connections instead of creating a new connection for every request.

It reduces connection setup overhead and helps control the number of simultaneous database connections. Pool size and timeouts should be configured according to the database capacity and application workload.

Part 2 — Detailed Explanation

Creating a database connection can require authentication, network setup, and other work. Reusing existing connections can improve efficiency.

For example, many Node.js database drivers and ORMs provide connection pools:

const mysql = require("mysql2/promise");

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
});

Queries can then use the pool rather than opening a new connection every time.

A larger pool is not always better. If many application instances each create a large pool, the total number of database connections may exceed the database's capacity.

33. What are database indexes?

Part 1 — Interview Answer

A database index is a data structure that helps the database locate records efficiently without scanning every record in a table or collection.

Indexes can significantly improve read performance, but they require storage and add overhead to inserts, updates, and deletes.

Part 2 — Detailed Explanation

Suppose you frequently search users by email. Without an appropriate index, the database may need to examine many records.

In MongoDB:

db.users.createIndex({ email: 1 });

In MySQL:

CREATE INDEX idx_users_email
ON users(email);

The database can use the index to speed up suitable queries.

Indexes should match real query patterns. A poorly chosen index can waste storage or provide little benefit. Use tools such as MongoDB's explain() or MySQL's EXPLAIN to inspect query plans.

34. How do you prevent SQL and NoSQL injection?

Part 1 — Interview Answer

I prevent injection attacks by validating user input, using parameterized SQL queries or safe database-driver methods, avoiding unsafe query construction, and applying least-privilege database permissions.

For MongoDB, I avoid passing untrusted objects directly into query filters and use validated fields and explicit query operators.

Part 2 — Detailed Explanation

Unsafe SQL example:

const query =
  `SELECT * FROM users WHERE email = '${email}'`;

This is dangerous because untrusted input is inserted directly into SQL syntax.

Safer example using parameterized SQL:

const [rows] = await pool.execute(
  "SELECT * FROM users WHERE email = ?",
  [email]
);

The driver treats the supplied email as a parameter rather than executable SQL syntax.

For MongoDB, avoid accepting an arbitrary query object directly from the client:

// Avoid using req.body directly as a MongoDB filter.
const user = await User.findOne(req.body);

Instead, validate the expected fields and build the filter yourself:

const email = String(req.body.email || "").trim();

const user = await User.findOne({ email });

Validation, safe query construction, and correct database permissions should be used together.

35. What are streams and buffers in Node.js?

Part 1 — Interview Answer

A Buffer represents binary data, such as file contents or network data. Streams provide an interface for processing data incrementally instead of loading the entire dataset into memory at once.

Streams are useful for large files, uploads, downloads, and data pipelines.

Part 2 — Detailed Explanation

A Buffer can hold binary data:

const buffer = Buffer.from("Hello Node.js");

console.log(buffer);
console.log(buffer.toString());

A stream processes data in chunks.

For example:

const fs = require("node:fs");

const stream = fs.createReadStream("large-file.txt");

stream.on("data", (chunk) => {
  console.log(`Received ${chunk.length} bytes`);
});

stream.on("error", (error) => {
  console.error("File reading failed:", error.message);
});

stream.on("end", () => {
  console.log("Finished reading file");
});

This lets the application process the file incrementally rather than requiring the entire file to be held in memory at once.

36. How do readable and writable streams work?

Part 1 — Interview Answer

A readable stream provides data for an application to consume. A writable stream accepts data from an application.

Node.js also provides duplex streams, which support both reading and writing, and transform streams, which modify data as it passes through.

Part 2 — Detailed Explanation

A readable stream might read a file, while a writable stream might write data to another file.

Example:

const fs = require("node:fs");

const source = fs.createReadStream("input.txt");
const destination = fs.createWriteStream("output.txt");

source.on("error", console.error);
destination.on("error", console.error);

destination.on("finish", () => {
  console.log("Copy completed");
});

source.pipe(destination);

The pipe() method connects the readable stream to the writable stream and coordinates data flow.

For more complex pipelines, stream.pipeline() is often preferable because it provides better error propagation and stream cleanup.

37. What is stream backpressure?

Part 1 — Interview Answer

Backpressure occurs when a writable destination cannot process data as quickly as a readable source produces it.

Node.js streams help manage backpressure so a fast producer does not overwhelm a slower consumer with excessive buffered data.

Part 2 — Detailed Explanation

Imagine reading a very large file and writing it to a slow network connection.

If the source produces data too quickly, memory usage can increase.

Using pipe() allows Node.js to coordinate the flow:

const fs = require("node:fs");

fs.createReadStream("large-file.bin")
  .pipe(fs.createWriteStream("copy.bin"));

When manually writing to a writable stream, check the return value of write().

const canContinue = writable.write(chunk);

if (!canContinue) {
  writable.once("drain", () => {
    // Resume writing when the destination is ready.
  });
}

The full implementation must also handle errors and stream completion. Prefer pipe() or pipeline() unless you need to manage the flow manually.

38. How do you process large files efficiently?

Part 1 — Interview Answer

I process large files using streams and incremental processing instead of loading the entire file into memory. I also handle backpressure, validate input, manage errors, and move expensive processing to background workers when necessary.

Part 2 — Detailed Explanation

Avoid reading a very large file into memory when you only need to process it line by line.

For a simple file copy:

const fs = require("node:fs");
const { pipeline } = require("node:stream/promises");

async function copyFile() {
  await pipeline(
    fs.createReadStream("large-file.bin"),
    fs.createWriteStream("copy.bin")
  );

  console.log("File copied successfully");
}

copyFile().catch(console.error);

The pipeline handles data flow and propagates stream errors.

For CSV imports, log processing, and large uploads, you can process data in chunks and save results incrementally.

Also consider file-size limits, temporary-file cleanup, access permissions, and whether the processing task should run asynchronously in a background job.

39. How do you manage database transactions?

Part 1 — Interview Answer

A database transaction groups multiple database operations into one logical unit of work. Transactions help maintain consistency by ensuring operations are committed together or rolled back when necessary.

I use transactions when related operations must succeed or fail as a unit, such as transferring money between accounts or creating an order and updating inventory.

Part 2 — Detailed Explanation

Suppose an application transfers money between two accounts.

The operation must debit one account and credit another. If only one update succeeds, the database may become inconsistent.

A transaction follows this general pattern:

  1. Begin the transaction.

  2. Execute the related operations.

  3. Commit if everything succeeds.

  4. Roll back if an operation fails.

A MySQL example:

const connection = await pool.getConnection();

try {
  await connection.beginTransaction();

  await connection.execute(
    "UPDATE accounts SET balance = balance - ? WHERE id = ?",
    [100, senderId]
  );

  await connection.execute(
    "UPDATE accounts SET balance = balance + ? WHERE id = ?",
    [100, receiverId]
  );

  await connection.commit();
} catch (error) {
  await connection.rollback();
  throw error;
} finally {
  connection.release();
}

This is a simplified example. A production implementation must also verify that both accounts exist, check sufficient funds, prevent invalid balances, and handle concurrent requests safely.

MongoDB also supports transactions for supported deployments and operations, though the data model and transaction requirements should be considered carefully.

40. How would you optimize a slow database query?

Part 1 — Interview Answer

I first measure the query's performance and inspect its execution plan. Then I check indexes, filters, joins, sorting, returned fields, and the amount of data being processed.

I also examine connection pooling, query frequency, application-level caching, and database resource utilization before making changes.

Part 2 — Detailed Explanation

A query can be slow for several reasons:

  • It scans too many records.

  • It uses missing or unsuitable indexes.

  • It returns unnecessary fields.

  • It performs expensive joins or sorting.

  • It retrieves too much data in one request.

  • It competes with other queries for database resources.

For example, in MongoDB:

const users = await User.find({
  status: "active",
})
  .select("name email")
  .limit(50)
  .lean();

This example limits the result size and selects only a few fields. lean() can reduce Mongoose document overhead when full document behavior is unnecessary.

However, optimization should be guided by measurement. Use query execution plans and production metrics to identify the actual bottleneck before adding indexes or caching.

5. Security, Performance, and Scalability

41. What is the difference between authentication and authorization?

Part 1 — Interview Answer

Authentication verifies who a user is. Authorization determines what an authenticated user is allowed to do.

For example, logging in verifies a user's identity, while checking whether that user can delete a particular record is an authorization decision.

Part 2 — Detailed Explanation

Imagine an application with users and administrators.

Authentication confirms that a user has valid credentials or a valid session.

Authorization checks whether the user has permission to perform an action.

Example:

function requireAdmin(req, res, next) {
  if (req.user?.role !== "admin") {
    return res.status(403).json({
      message: "Access denied",
    });
  }

  next();
}

This middleware assumes that an earlier authentication middleware has securely populated req.user.

A secure application must check permissions on the server for every protected operation. Hiding a button in the frontend is not sufficient authorization.

42. What is the difference between JWT and session-based authentication?

Part 1 — Interview Answer

Session-based authentication stores session state on the server and typically gives the client a session identifier. JWT-based authentication uses a signed token that contains claims and can be validated by a server.

Sessions make centralized invalidation straightforward, while JWTs can simplify certain distributed verification scenarios. The right approach depends on security, deployment, revocation, and client requirements.

Part 2 — Detailed Explanation

With session-based authentication:

  1. The user logs in.

  2. The server creates a session.

  3. The client receives a session ID, usually through a cookie.

  4. The server looks up the session on subsequent requests.

With JWT-based authentication:

  1. The user logs in.

  2. The server issues a signed token.

  3. The client sends the token with subsequent requests.

  4. The server validates the token and its claims.

JWTs are not automatically encrypted. A signed JWT's payload can often be decoded by anyone who has the token.

For browser applications, use appropriate cookie settings, HTTPS, CSRF protections where relevant, and secure token-storage practices. JWTs also require a deliberate strategy for expiration and revocation.

43. Where should secrets and environment variables be stored?

Part 1 — Interview Answer

Secrets should be stored outside source code, using a secrets manager or the hosting platform's secure environment-variable configuration.

I avoid committing credentials to Git, exposing private keys in frontend code, or logging sensitive values. Access to secrets should follow the principle of least privilege.

Part 2 — Detailed Explanation

Examples of secrets include:

  • Database passwords.

  • Private API keys.

  • JWT signing secrets.

  • Cloud provider credentials.

  • Third-party service tokens.

For local development, a .env file can be convenient:

DATABASE_URL=your_database_url
JWT_SECRET=your_secret_value

Add .env to .gitignore.

For production, use the secure configuration mechanism provided by your deployment platform or a dedicated secrets manager.

If a secret is accidentally committed or exposed, removing it from the latest version of the file is not enough. Rotate or revoke the exposed credential.

44. How do you secure a Node.js API?

Part 1 — Interview Answer

I secure a Node.js API through input validation, authentication, authorization, secure secret management, rate limiting, HTTPS, appropriate security headers, safe database queries, and careful error handling.

I also keep dependencies updated, limit request sizes, monitor suspicious activity, and avoid trusting client-supplied data.

Part 2 — Detailed Explanation

Security requires multiple layers.

For example, an Express API might use security headers and request-size limits:

const helmet = require("helmet");

app.use(helmet());
app.use(express.json({
  limit: "100kb",
}));

Install Helmet with:

npm install helmet

Additional security measures include:

  • Validate every request on the server.

  • Verify authorization for each protected resource.

  • Use parameterized SQL queries or safe database filters.

  • Configure CORS for the intended frontend origins.

  • Apply rate limits to sensitive endpoints.

  • Use HTTPS in production.

  • Hash passwords with a suitable password-hashing algorithm.

  • Review and update dependencies.

  • Avoid exposing stack traces and internal errors to clients.

Security is not a single middleware package. It requires appropriate design, configuration, testing, and monitoring.

45. How do you prevent brute-force attacks?

Part 1 — Interview Answer

I reduce brute-force attacks by applying rate limits, progressive delays or temporary lockouts where appropriate, monitoring repeated failures, and adding stronger verification for suspicious login activity.

I also store passwords using a suitable password-hashing algorithm and avoid revealing whether a particular email address or username exists.

Part 2 — Detailed Explanation

A brute-force attacker repeatedly attempts passwords or verification codes until one succeeds.

For login endpoints, useful defenses include:

  • Per-IP and per-account attempt limits.

  • Rate limiting across multiple application instances.

  • Temporary restrictions on repeated failed attempts.

  • Multi-factor authentication where appropriate.

  • Alerts for suspicious activity.

  • Secure password hashing with Argon2id, scrypt, or another appropriate algorithm.

Be careful with permanent account lockouts: attackers may use them to deny service to legitimate users.

Rate limiting should be applied to password reset and OTP endpoints as well as login endpoints.

46. How do you identify memory leaks in Node.js?

Part 1 — Interview Answer

I identify memory leaks by monitoring memory usage over time, reproducing the workload, and using heap snapshots and profiling tools to find objects that remain in memory unexpectedly.

Common causes include unbounded caches, retained references, event listeners that are not removed, and timers or background tasks that are never cleaned up.

Part 2 — Detailed Explanation

Start by monitoring memory:

setInterval(() => {
  const memory = process.memoryUsage();

  console.log({
    rss: memory.rss,
    heapUsed: memory.heapUsed,
    heapTotal: memory.heapTotal,
  });
}, 10000);

If memory usage continually increases under a repeatable workload and does not stabilize, investigate further.

Useful tools include:

  • Node.js inspector and Chrome DevTools.

  • Heap snapshots.

  • CPU and heap profiling.

  • Production monitoring and metrics.

Look for objects that remain referenced after they should have been released.

Avoid capturing heap snapshots indiscriminately in production: they may consume substantial memory and can contain sensitive application data.

47. How do you monitor a production Node.js application?

Part 1 — Interview Answer

I monitor production applications using structured logs, application metrics, error tracking, distributed tracing, and infrastructure monitoring.

Important metrics include request latency, error rates, throughput, CPU usage, memory usage, event-loop delay, database performance, and external service failures.

Part 2 — Detailed Explanation

Monitoring helps you detect problems before they affect many users.

For example, a slow API response could be caused by a database query, a third-party API, or CPU saturation.

Useful monitoring categories include:

  • Logs: Record errors and important application events.

  • Metrics: Track response time, request count, memory, and CPU.

  • Tracing: Follow a request across multiple services.

  • Alerts: Notify the team when defined thresholds are exceeded.

Tools may include OpenTelemetry, Prometheus, Grafana, and error-monitoring platforms.

Avoid logging passwords, access tokens, or sensitive personal information. Correlation IDs can help connect related log entries without exposing secrets.

48. How do you implement graceful shutdown in Node.js?

Part 1 — Interview Answer

Graceful shutdown allows a server to stop accepting new requests, finish in-flight work where possible, and close database connections and other resources before exiting.

I handle termination signals, initiate server shutdown, apply a timeout, and ensure cleanup happens even when an error occurs.

Part 2 — Detailed Explanation

A simplified HTTP server example:

const http = require("node:http");
const app = require("./app");

const server = http.createServer(app);

server.listen(3000);

function shutdown(signal) {
  console.log(`${signal} received`);

  server.close((error) => {
    if (error) {
      console.error("Server shutdown failed");
      process.exitCode = 1;
    }

    // Close database pools and other resources here.
  });
}

process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT", () => shutdown("SIGINT"));

This is a starting point rather than a complete production implementation.

A robust implementation should also:

  • Stop accepting new work.

  • Mark the instance as unready when health checks are used.

  • Close database pools and message-broker connections.

  • Handle shutdown timeouts.

  • Avoid starting duplicate shutdown sequences.

  • Exit with an appropriate status after cleanup.

49. How would you scale a Node.js application?

Part 1 — Interview Answer

I scale a Node.js application by measuring bottlenecks first, then applying techniques such as horizontal scaling, load balancing, database optimization, caching, background job processing, and connection pooling.

I keep application instances as stateless as practical and store shared session or job state in appropriate external systems.

Part 2 — Detailed Explanation

Scaling can involve several layers.

Application layer

Run multiple instances behind a load balancer. Depending on the deployment, you can use containers, a process manager, orchestration, or managed application services.

Database layer

Use suitable indexes, optimize queries, and configure connection pools carefully. If necessary, consider replicas or other database scaling strategies.

Caching layer

Cache appropriate frequently accessed data with a clear expiration and invalidation strategy.

Background processing

Move time-consuming work, such as sending emails or processing large files, to a job queue and worker processes.

Monitoring

Track response times, error rates, CPU usage, memory usage, and database saturation to determine where scaling is needed.

Adding more server instances will not solve every problem. A shared database, external API, or unbounded workload may remain the bottleneck.

50. How would you design a production-ready Node.js backend?

Part 1 — Interview Answer

I would design a production-ready Node.js backend with a clear architecture, validated API contracts, centralized error handling, secure authentication and authorization, an appropriate database model, structured logging, monitoring, automated tests, and a reliable deployment process.

I would also consider scalability, graceful shutdown, rate limiting, secrets management, database migrations, backups, and operational recovery.

Part 2 — Detailed Explanation

A production backend should be more than a collection of routes. It needs a structure that makes the application secure, testable, maintainable, and observable.

A possible project structure is:

src/
├── config/
├── routes/
├── controllers/
├── services/
├── repositories/
├── middleware/
├── validators/
├── utils/
└── app.js

server.js
package.json
.env

The responsibilities might be:

  • Routes: Define endpoints and connect them to handlers.

  • Controllers: Handle HTTP requests and responses.

  • Services: Implement business logic.

  • Repositories: Encapsulate database operations where useful.

  • Middleware: Handle authentication, logging, and shared request processing.

  • Validators: Validate incoming data.

  • Config: Manage application configuration.

A production-ready system should also have:

  1. Authentication and resource-level authorization.

  2. Secure input validation and database access.

  3. Automated unit and integration tests.

  4. Appropriate database indexes and transactions.

  5. Centralized logs, metrics, and alerts.

  6. Rate limits and request-size limits.

  7. Health checks and graceful shutdown.

  8. A repeatable deployment pipeline.

  9. Database backups and recovery procedures.

  10. Documentation for APIs and operational procedures.

The architecture should fit the project's size. A well-structured monolith can be a better starting point than introducing microservices before they are needed.

Bonus: How to Prepare for a Node.js Interview

Knowing the answers is important, but interviewers also want to know whether you can apply those concepts in real projects.

Use this preparation strategy:

1. Understand the concept. Be able to explain the event loop, middleware, Promises, streams, and database indexes in simple language.

2. Practice coding. Build a REST API with CRUD operations, validation, authentication, pagination, and error handling.

3. Explain trade-offs. For example, discuss when you would choose MongoDB over MySQL, or worker threads over background jobs.

4. Prepare real examples. Be ready to explain a bug you fixed, a performance issue you investigated, or a security improvement you implemented.

5. Practice follow-up questions. Interviewers may ask why a solution works, what happens when it fails, and how it behaves under higher traffic.

Final Thoughts

Node.js interviews cover much more than JavaScript syntax. A strong backend developer understands asynchronous execution, HTTP, databases, security, performance, and application architecture.

Use these 50 questions as a checklist. Practice giving the short interview answer first, then expand with the detailed explanation and a practical example.

The goal is not to memorize every sentence. It is to understand the concepts well enough to explain your decisions clearly and confidently during an interview.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘