or

Node.js Interview Questions

14 questions · For backend and full-stack developers

Node.js interviews focus on how well you understand the event loop and asynchronous code, and how you build and scale real APIs.

Practise these out loud with AI

Freshers (0–2 years)

Practise this level
  1. 1. What is the event loop in Node.js?

    What they look for: A single thread runs callbacks from a queue while I/O happens in the background. Mention its phases at a high level.

    Recommended Answer:
    The Event Loop is the engine that allows Node.js to perform non-blocking I/O operations despite being single-threaded. It delegates operations like file reading, network calls, or database queries to the OS kernel or libuv thread pool. The loop continuously monitors the Call Stack and moves callbacks from queues (Timers, Poll, Check) to the stack when it is empty.
    // Non-blocking execution example
    console.log('1. Start');
    setTimeout(() => console.log('2. Timeout Callback'), 0);
    Promise.resolve().then(() => console.log('3. Microtask Promise'));
    console.log('4. End');
    // Output order: 1, 4, 3, 2
  2. 2. What is the difference between callbacks, promises and async/await?

    What they look for: Same async work, increasingly readable. Show error handling in each.

    Recommended Answer:
    Callbacks pass a function to be executed when an async operation finishes (often leading to 'Callback Hell'). Promises provide a cleaner chaining mechanism (.then/.catch) representing a future value in Pending, Fulfilled, or Rejected state. Async/await is syntactic sugar over Promises, making asynchronous code read synchronously and cleanly with try/catch blocks.
    // Modern async/await with try-catch
    async function fetchUser(id) {
      try {
        const res = await api.get(`/users/${id}`);
        return res.data;
      } catch (err) {
        logger.error('Failed to fetch user:', err);
        throw err;
      }
    }
  3. 3. What is middleware in Express?

    What they look for: Functions that run in order on each request. Give examples like logging, auth and error handling.

    Recommended Answer:
    Middleware functions have access to the Request object (req), the Response object (res), and the next middleware function (next) in the HTTP pipeline. They can execute code, modify req/res objects, end request-response cycles, or call next() to pass control to the next handler. Common uses: auth checks, request logging (Morgan), CORS, and body parsing.
    const authMiddleware = (req, res, next) => {
      const token = req.headers['authorization'];
      if (!token) return res.status(401).json({ error: 'Unauthorized' });
      req.user = verifyToken(token);
      next();
    };
  4. 4. What is the difference between require and import?

    What they look for: CommonJS versus ES modules — loading behaviour and how to configure each.

    Recommended Answer:
    require() belongs to CommonJS (CJS). It loads synchronously at runtime, returns the module.exports object, and can be used dynamically inside if-blocks. import belongs to ES Modules (ESM). It is parsed statically at compile time, supports tree-shaking, and requires 'type': 'module' in package.json.
    // CommonJS
    const express = require('express');
    
    // ES Module
    import express from 'express';
  5. 5. How do you read environment variables and keep secrets safe?

    What they look for: process.env, a .env file only in development, and never committing secrets.

    Recommended Answer:
    Read environment variables using process.env.<VARIABLE_NAME>. In development, use dotenv (with a .env file). In production, inject variables through Docker, AWS Secrets Manager, or Kubernetes secrets. Never commit .env files to Git repositories—always add .env to .gitignore and provide an empty .env.example.
    import dotenv from 'dotenv';
    dotenv.config();
    const PORT = process.env.PORT || 5000;
    const DB_URL = process.env.DATABASE_URL;

Mid-level (2–5 years)

Practise this level
  1. 6. What are streams and when would you use them?

    What they look for: Processing data in chunks, such as large file uploads or downloads, without loading everything into memory.

    Recommended Answer:
    Streams handle reading or writing data in chunks piece-by-piece rather than buffering the entire content into RAM memory. Essential for processing large files (video streaming, CSV imports) or high-concurrency APIs without memory crashes. Four types exist: Readable, Writable, Duplex, and Transform.
    import fs from 'fs';
    // Memory-efficient piping
    const readStream = fs.createReadStream('large_input.csv');
    const writeStream = fs.createWriteStream('output.csv');
    readStream.pipe(writeStream);
  2. 7. How do you handle errors in an Express app?

    What they look for: Central error middleware, async error wrapping, and consistent error responses without leaking internals.

    Recommended Answer:
    Handle errors using a centralized error-handling middleware placed as the very last app.use() layer. Express identifies error middleware by its 4 arguments: (err, req, res, next). Always wrap async route handlers with an async wrapper utility (or use express-async-errors in Express 5) to prevent unhandled promise rejections.
    // Central Error Handler
    app.use((err, req, res, next) => {
      const status = err.statusCode || 500;
      logger.error(err.stack);
      res.status(status).json({ success: false, message: err.message || 'Server Error' });
    });
  3. 8. What blocks the event loop and how do you avoid it?

    What they look for: CPU-heavy work and sync APIs. Move work to worker threads or a queue.

    Recommended Answer:
    Heavy CPU tasks block the single-threaded event loop—such as parsing massive JSON strings, complex RegEx (ReDoS), cryptographic loops, or extensive array sorting. Avoid it by offloading heavy work to Worker Threads (worker_threads), spawning child processes, or delegating tasks to external queues like Redis / BullMQ.
    // Worker Threads for heavy CPU tasks
    import { Worker } from 'worker_threads';
    const runWorker = (data) => new Worker('./heavy-task.js', { workerData: data });
  4. 9. How do you implement authentication in an API?

    What they look for: JWT or session cookies, secure storage of passwords with bcrypt or argon2, and token expiry and refresh.

    Recommended Answer:
    Standard API authentication uses short-lived JWTs (JSON Web Tokens) for stateless authentication alongside secure HTTP-only refresh tokens stored in Redis for session revocation. Password storage must use slow, salted cryptographic hashing algorithms (Argon2 or Bcrypt).
    import bcrypt from 'bcrypt';
    const saltRounds = 12;
    const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);
    const isMatch = await bcrypt.compare(inputPassword, hashedPassword);
  5. 10. How do you validate request data?

    What they look for: A schema library like zod or Joi at the edge of every route.

    Recommended Answer:
    Validate incoming request payloads at the boundary using schema validation libraries like Zod or Joi before allowing controllers to execute business logic. This eliminates malformed inputs, sanitizes data against injections, and auto-generates TypeScript types.
    import { z } from 'zod';
    const userSchema = z.object({
      email: z.string().email(),
      password: z.string().min(8)
    });
    const validated = userSchema.parse(req.body);

Senior (5+ years)

Practise this level
  1. 11. How do you scale a Node.js service?

    What they look for: Stateless instances behind a load balancer, cluster or containers, caching, and queues for slow work.

  2. 12. How do you find a memory leak in Node.js?

    What they look for: Heap snapshots, watching memory over time, and common causes like global caches and unremoved listeners.

  3. 13. How do you secure a Node.js API?

    What they look for: Input validation, rate limiting, security headers, dependency audits, and least-privilege database access.

  4. 14. How do you design for graceful shutdown?

    What they look for: Stop accepting new requests, finish in-flight ones, close database and queue connections, then exit.

Frequently asked questions

Do Node.js interviews ask JavaScript fundamentals?

Yes — closures, this, prototypes and promises are common, especially in the first round.

Is TypeScript expected for Node.js roles?

Increasingly yes. Many backend teams use TypeScript by default.

Which framework should I know besides Express?

Express is enough for most interviews. NestJS or Fastify are a plus if the job mentions them.

More interview questions