Skip to content
Laviyx Learn

Try

Node.js and Express Interview Questions

Frequently asked Node.js, Express and back-end JavaScript interview questions on the event loop, modules, npm, streams, middleware, REST APIs, databases, authentication, security and scaling, with hints and answers.

15 questions · Updated

  1. 1.What is Node.js, and what is it good for?

    BeginnerConceptBasics
    Show hint

    JavaScript outside the browser, non-blocking.

    Show solution

    A JavaScript runtime built on Chrome's V8 engine, with APIs for files, networking and processes. Its non-blocking, event-driven I/O suits web servers and APIs, real-time apps and tooling. It is a poor fit for long CPU-heavy work on the main thread, which blocks every other request.

  2. 2.How does single-threaded Node.js serve many users at once?

    BeginnerConceptEvent loop
    Show hint

    Who waits for the disk and network?

    Show solution

    Slow I/O is handed to the operating system and libuv's thread pool. While it is in progress, the JavaScript thread keeps handling other requests; when an operation completes, its callback is queued and the event loop runs it. Many requests are therefore in progress concurrently, though only one piece of JavaScript runs at any moment.

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

    BeginnerConceptModules
    Show hint

    require or import?

    Show solution

    CommonJS uses require() and module.exports and is Node's original system (the default without "type": "module"). ES modules use import/export, are the JavaScript standard, support top-level await, and are enabled with "type": "module" or .mjs. In ES modules, use import.meta.dirname instead of __dirname.

  4. 4.Why commit package-lock.json?

    BeginnerConceptnpm
    Show hint

    Same versions everywhere.

    Show solution

    It records the exact version of every installed package, including nested dependencies, so every developer, CI run and server installs identical code. npm ci installs exactly what it lists. Without it, version ranges such as ^1.11.23 could resolve to different versions over time.

  5. 5.In what order do console.log, setTimeout(0), a resolved promise's then and process.nextTick run?

    IntermediateOutput predictionEvent loop
    Show hint

    Synchronous code, microtasks, then timers.

    Show solution

    Synchronous code first, then microtasks, then timers. Inside callbacks and in CommonJS, process.nextTick runs before promise callbacks; at the top level of an ES module, promise callbacks queued there run first. The setTimeout(..., 0) callback runs last, in the timers phase.

  6. 6.When would you use streams instead of readFile?

    IntermediateScenarioStreams
    Show hint

    Memory.

    Show solution

    For large or unbounded data (big files, uploads, logs, network responses). Streams process data chunk by chunk with constant memory, start producing output immediately, and handle backpressure. Use pipeline() from node:stream/promises to connect them with proper error handling.

  7. 7.Why does the order of app.use calls matter in Express?

    IntermediateConceptExpress
    Show hint

    Middleware runs top to bottom.

    Show solution

    Middleware and routes run in registration order. Body parsers must come before routes that read req.body, authentication before the routes it protects, a 404 handler after all routes, and the error handler (four parameters) last so it can catch errors from everything above it.

  8. 8.What happens when an async Express route handler throws?

    IntermediateConceptError handling
    Show hint

    It changed in Express 5.

    Show solution

    In Express 5, a thrown error or rejected promise in a route handler is passed to error-handling middleware automatically. In Express 4, async rejections were not caught, so handlers needed try/catch with next(err) or a wrapper; otherwise the request hung or the process logged an unhandled rejection.

  9. 9.How do you prevent SQL injection in Node.js?

    IntermediateConceptDatabases
    Show hint

    Placeholders.

    Show solution

    Use parameterised queries (WHERE id = ? with values passed separately) or an ORM/query builder that parameterises for you; never concatenate user input into SQL. Also validate input and give the database user only the permissions it needs.

  10. 10.How should passwords be stored?

    IntermediateConceptSecurity
    Show hint

    Slow and salted.

    Show solution

    As salted hashes from a deliberately slow algorithm (bcrypt, scrypt or Argon2), never in plain text or with fast hashes like SHA-256. Compare with a constant-time function, rate-limit login attempts, and return the same error for unknown users and wrong passwords.

  11. 11.When would you choose sessions over JWTs?

    IntermediateScenarioAuthentication
    Show hint

    Revocation.

    Show solution

    Sessions (server-side data plus a session id cookie) are easy to revoke instantly and keep data off the client; they need shared storage when scaled. JWTs need no server storage and work well across services, but cannot be revoked before expiry without extra work. Choose sessions for typical web apps needing instant logout; JWTs (short-lived, with refresh tokens) for distributed APIs and mobile clients.

  12. 12.A route that resizes images makes the whole API slow. Why, and how do you fix it?

    AdvancedDebuggingPerformance
    Show hint

    The event loop is blocked.

    Show solution

    CPU-heavy work runs on the single JavaScript thread, so while one image is processed no other request is handled. Move the work to worker threads, a separate service, or a background job queue (respond 202 Accepted and process asynchronously), and use libraries that run natively off the main thread.

  13. 13.How do you scale a Node.js API to many servers?

    AdvancedDesignScaling
    Show hint

    Stateless instances.

    Show solution

    Keep instances stateless (sessions, caches and rate-limit counters in Redis or the database), run several instances behind a load balancer, cache aggressively, use connection pooling and read replicas, and move slow work to queues and workers. Add graceful shutdown and health checks for safe rolling deploys.

  14. 14.How would you investigate a memory leak in a Node.js service?

    AdvancedDebuggingPerformance
    Show hint

    Heap snapshots over time.

    Show solution

    Confirm the heap grows steadily (process.memoryUsage(), metrics), take heap snapshots at intervals with --inspect or v8.writeHeapSnapshot(), and compare what is retained. Look for unbounded caches, listeners added repeatedly, uncleared timers and closures holding large objects; fix the retention and bound caches.

  15. 15.What is an idempotency key, and why do payment APIs use one?

    AdvancedConceptReliability
    Show hint

    Retries after a timeout.

    Show solution

    A unique key sent with a request so the server can recognise repeats. If a client retries after a timeout, the server returns the stored result for that key instead of performing the action again, so a payment is never charged twice.

Review the lessons