Blog

Node.js & Express.js Interview Questions: From Junior to Principal Engineer (2026)

By Ahsan Hafeez · 2026-11-10

Whether you are preparing for your first backend role or targeting a principal engineer position, Node.js interviews test different things at every level. This guide covers 50+ questions organized by seniority so you can focus on what matters for your target role.

Core Foundations

Q: What are the six phases of the Node.js event loop?

The event loop runs through six phases in order: timers (executes setTimeout/setInterval callbacks), pending callbacks (I/O callbacks deferred from the previous cycle), idle/prepare (internal housekeeping), poll (retrieves new I/O events and executes their callbacks), check (runs setImmediate callbacks), and close callbacks (handles socket.on('close') and similar). The poll phase is where the loop spends most of its time, waiting for new I/O if no timers are scheduled.

Q: How does the libuv thread pool work?

Libuv maintains a thread pool (default 4 threads) for operations that cannot be done asynchronously at the OS level, like DNS lookups via dns.lookup(), file system calls, and some crypto operations. You can increase the pool size by setting the UV_THREADPOOL_SIZE environment variable up to 1024. Network I/O does not use the thread pool because it relies on OS-level async primitives like epoll, kqueue, or IOCP.

Q: How does V8 compile and optimize JavaScript?

V8 uses a two-tier compilation pipeline. The Ignition interpreter quickly generates bytecode for fast startup, then the TurboFan optimizing compiler identifies hot functions and compiles them to highly optimized machine code. V8 also uses hidden classes (internal shapes) to speed up property access and inline caches to avoid repeated lookups.

Q: How does V8 garbage collection work?

V8 splits the heap into a young generation (small, collected frequently using Scavenge) and an old generation (large, collected less often using Mark-Sweep and Mark-Compact). Short-lived objects get allocated in the young generation and promoted to old generation if they survive two scavenge cycles. This generational approach keeps pause times low for most requests.

Q: What is the difference between process.nextTick() and setImmediate()?

process.nextTick() fires after the current operation completes but before the event loop continues to the next phase. setImmediate() fires during the check phase of the event loop, after the poll phase. In practice, nextTick callbacks always execute before setImmediate callbacks, and overusing nextTick can starve I/O because it keeps running before the loop moves on.

Q: How does Node.js handle async I/O under the hood?

When you call an async operation like fs.readFile(), Node.js delegates it to libuv, which either uses the OS async mechanism (epoll/kqueue/IOCP for network) or the thread pool (for file I/O and DNS). Once the operation completes, libuv queues the callback, and the event loop picks it up during the appropriate phase. The JavaScript thread never blocks because the actual I/O happens on separate OS threads or kernel primitives.

Q: What are Node.js streams and how does backpressure work?

Streams are objects that let you read or write data piece by piece instead of loading everything into memory. There are four types: Readable, Writable, Duplex, and Transform. Backpressure happens when the writable destination cannot consume data as fast as the readable source produces it. The stream.write() method returns false when the internal buffer is full, signaling the source to pause until the drain event fires.

Q: What is the difference between CommonJS require and ESM import?

CommonJS (require) loads modules synchronously, evaluates them at runtime, and returns a cached copy of module.exports. ESM (import) is statically analyzed at parse time, supports tree-shaking, and uses live bindings so you always see the latest exported value. In Node.js, .mjs files or "type": "module" in package.json enable ESM. You can import CommonJS modules from ESM but not the other way around without dynamic import().

Q: Node.js is single-threaded but non-blocking. What does this actually mean?

There is one main thread running your JavaScript code and the event loop. That single thread never waits for I/O because all I/O operations are delegated to the OS or libuv thread pool and handled via callbacks. This means one request does not block another while waiting for a database response. But CPU-intensive work on the main thread will block everything because there is no preemption.

Junior Level

Q: How does the Express middleware chain work?

Middleware functions execute in the order they are added via app.use() or route-specific methods. Each middleware receives req, res, and a next function. Calling next() passes control to the next middleware in the stack. If you do not call next() or send a response, the request hangs indefinitely.

Q: What is the req/res lifecycle in Express?

A request comes in and Express matches it against registered routes and middleware in order. The req object carries incoming data (headers, body, params, query), and the res object has methods to send back a response (res.json(), res.send(), res.status()). The cycle ends when a middleware or route handler sends a response. Any middleware after that point does not execute unless it was called before res was sent.

Q: How do route params, query strings, and body differ?

Route params are part of the URL path (e.g., /users/:id gives req.params.id). Query strings come after the ? in the URL (e.g., ?page=2 gives req.query.page). The request body carries POST/PUT data and requires a body-parsing middleware like express.json() to populate req.body. Params identify a specific resource, queries filter or paginate, and body carries the payload.

Q: How does error handling middleware work in Express?

Error-handling middleware takes four arguments: (err, req, res, next). Express skips regular middleware and jumps to error handlers when next(err) is called or an error is thrown in an async handler. You should define error middleware after all routes. For async route handlers, you need to catch promise rejections and pass them to next() or use a wrapper like express-async-errors.

Q: How do you serve static files in Express?

Use express.static() middleware: app.use(express.static('public')). This serves files from the public directory at the root URL. You can mount it on a path prefix like app.use('/assets', express.static('public')). For production, put a CDN or Nginx in front instead of serving static files through Node.js.

Q: How do you set up CORS in Express?

Install the cors package and use it as middleware: app.use(cors()). For specific origins, pass an options object: cors({ origin: 'https://myapp.com' }). You can also configure allowed methods, headers, and credentials. Without CORS headers, browsers block cross-origin requests from frontend code.

Q: How should you manage environment variables?

Use dotenv to load a .env file into process.env during development. Never commit .env files to version control. In production, set environment variables through your hosting platform or container orchestration. Always validate required env vars at startup and fail fast if any are missing.

Q: What makes a good REST API design?

Use nouns for resources (/users, /orders), HTTP verbs for actions (GET to read, POST to create, PUT/PATCH to update, DELETE to remove), and proper status codes (200, 201, 400, 404, 500). Keep URLs consistent and predictable. Return meaningful error messages with a consistent error response shape.

Q: How do you parse and validate JSON request bodies?

Use express.json() middleware to parse incoming JSON. This populates req.body with the parsed object. Always validate the shape and types of incoming data using a library like Zod or Joi before passing it to your business logic. Reject invalid payloads with a 400 status and a clear error message.

Mid Level

Q: What are the main authentication patterns for Express apps?

JWT (JSON Web Tokens) is stateless: the server signs a token on login and the client sends it in the Authorization header on each request. Session-based auth stores a session ID in a cookie and keeps session data server-side (often in Redis). OAuth delegates login to a third-party provider like Google or GitHub. JWT works well for APIs and microservices. Sessions are simpler for server-rendered apps.

Q: How do you implement rate limiting and what does Helmet do?

Rate limiting restricts how many requests a client can make in a time window. Use express-rate-limit for basic limiting or a Redis-backed store for distributed setups. Helmet sets security-related HTTP headers like Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security. Both should be applied early in the middleware chain.

Q: What are database connection pooling best practices?

Create a single connection pool at app startup and reuse it across requests. Never open a new connection per request. Pools like pg.Pool or Prisma's built-in pool manage a set of idle connections ready for queries. Set pool size based on your expected concurrency, and always release connections back to the pool after use.

Q: How do you handle file uploads in Express?

Use multer middleware for multipart/form-data uploads. Multer can store files on disk or in memory and gives you control over file size limits, allowed types, and field names. For large files, stream the upload directly to cloud storage (S3, GCS) instead of buffering in memory. Always validate file type and size on the server, never trust the client.

Q: How do you add WebSocket support alongside Express?

Use the ws library or Socket.io alongside your Express HTTP server. Create the WebSocket server on the same HTTP server instance so both share the same port. Express handles REST endpoints while WebSockets handle real-time bidirectional communication. Socket.io adds reconnection, rooms, and fallback to polling, but ws is lighter if you only need raw WebSockets.

Q: When should you use a job queue and which one?

Use a job queue for tasks that are slow (sending emails, processing images), need retry logic, or should run on a schedule. BullMQ is the standard choice for Node.js, backed by Redis. It supports delayed jobs, repeatable jobs, rate-limited queues, and concurrency control. Run queue workers in separate processes from your API server to keep request latency low.

Q: What is a good logging strategy for Node.js services?

Use Pino for structured JSON logging in production because it is the fastest Node.js logger. Log at different levels: error for failures, warn for degraded states, info for key business events, debug for development details. Include a request ID in every log line for tracing. Ship logs to a centralized system like ELK, Datadog, or Grafana Loki.

Q: How should you version an API?

The most common approach is URL versioning: /api/v1/users, /api/v2/users. Header-based versioning (Accept: application/vnd.myapi.v2+json) is cleaner but harder to test in a browser. Keep old versions running for a deprecation period and communicate timelines clearly. In Express, mount versioned routers: app.use('/api/v1', v1Router).

Q: How do you validate complex input in Express?

Use Zod or Joi to define schemas for request bodies, params, and query strings. Create a reusable validation middleware that takes a schema and returns 400 with detailed errors if validation fails. Zod has strong TypeScript inference so your validated data is automatically typed. Validate at the controller boundary before any business logic runs.

Senior Level

Q: What are the main microservices communication patterns?

Synchronous: REST over HTTP for simple request-response, gRPC for high-throughput low-latency service-to-service calls with Protobuf serialization. Asynchronous: message queues (RabbitMQ, SQS) for task distribution, event streaming (Kafka) for event-driven systems. Use sync when you need an immediate response, async when you want loose coupling and resilience to downstream failures.

Q: How do you design a caching strategy for a Node.js service?

Layer your caches: in-process memory (node-cache or LRU) for hot data that changes rarely, Redis for shared state across instances, and CDN for static assets and API responses. Set TTLs based on how stale data can tolerate being. Use cache-aside (read from cache, miss goes to DB, write back to cache) as the default pattern. Invalidate explicitly on writes when staleness is not acceptable.

Q: How should you approach database migrations in production?

Use a migration tool (Prisma Migrate, knex migrations, or golang-migrate) that tracks which migrations have run. Migrations should be forward-only and idempotent. For zero-downtime deploys, use expand-and-contract: add the new column (expand), deploy code that writes to both old and new, backfill data, switch reads, then remove the old column (contract). Never run destructive migrations without a rollback plan.

Q: How do you instrument a Node.js service with OpenTelemetry?

Install @opentelemetry/sdk-node and configure it to auto-instrument HTTP, Express, and database libraries. The SDK captures traces (request flows across services), metrics (latency, throughput, error rate), and logs. Export to your backend (Jaeger, Grafana Tempo, Datadog) via OTLP. Initialize the SDK before importing any other modules so auto-instrumentation can patch libraries.

Q: How do you implement graceful shutdown?

Listen for SIGTERM and SIGINT signals. When received, stop accepting new connections, drain in-flight requests (give them a timeout), close database pools and Redis connections, flush log buffers, and then call process.exit(0). Without graceful shutdown, deploying kills active requests mid-flight. Set a hard timeout (e.g., 30 seconds) as a safety net to force exit if draining takes too long.

Q: When should you use cluster mode vs worker threads?

Cluster mode (via the cluster module or PM2) forks multiple processes that share the same server port. Each process has its own memory and event loop. Use it to utilize all CPU cores for handling HTTP traffic. Worker threads share memory via SharedArrayBuffer and are better for CPU-intensive tasks like parsing large JSON or image processing within a single logical process.

Q: How do you harden a Node.js API against common attacks?

For SQL injection, use parameterized queries or an ORM, never string concatenation. For XSS, sanitize user input and set Content-Security-Policy headers. For CSRF, use CSRF tokens or SameSite cookies. For SSRF, validate and whitelist outbound URLs, block private IP ranges. Use Helmet for header security. Run npm audit regularly and keep dependencies updated.

Q: What is the API gateway pattern and when do you need it?

An API gateway sits in front of your microservices and handles cross-cutting concerns: authentication, rate limiting, request routing, response transformation, and SSL termination. Use one when you have multiple backend services and want a single entry point for clients. Options include Kong, AWS API Gateway, or a custom Express gateway. It prevents clients from knowing about internal service topology.

Team Lead

Q: What should a Node.js service template include?

A production-ready template should include: project structure (routes, controllers, services, repositories), health check endpoint, graceful shutdown, structured logging, OpenTelemetry instrumentation, Dockerfile, CI/CD pipeline config, linting and formatting rules, and test scaffolding. This eliminates boilerplate debates and ensures every new service starts with production standards.

Q: How do you run incident response for Node.js services?

Define runbooks for common failures: high memory (likely a leak, capture a heap snapshot with v8.writeHeapSnapshot()), event loop lag (CPU-bound code blocking the loop, profile with clinic.js), connection pool exhaustion (check for unreleased connections). Set up PagerDuty or Opsgenie alerts on error rate spikes, latency p99, and memory usage. After every incident, run a blameless postmortem and update the runbook.

Q: How do you manage npm dependencies and security?

Pin exact versions in package-lock.json and commit it. Run npm audit weekly in CI and block merges with critical vulnerabilities. Use Dependabot or Renovate for automated dependency update PRs. Avoid installing packages with very few maintainers or downloads for critical paths. Review changelogs before major version bumps.

Q: What testing standards should a backend team follow?

Require unit tests for business logic (fast, no I/O), integration tests for API routes against a real database (use testcontainers or a Docker-based test DB), and contract tests for service-to-service boundaries. Set a coverage floor (80%+ on business logic, not on boilerplate). Run tests in CI on every PR. Flaky tests get fixed immediately or quarantined.

Q: How do you build a performance benchmarking culture?

Run load tests (k6, Artillery) against staging before every major release. Track p50, p95, and p99 latency over time as part of your deployment metrics. Set performance budgets: "this endpoint must respond in under 200ms at p99." Make benchmark results visible in dashboards. When performance degrades, the PR that caused it is responsible for the fix.

Q: What belongs in an on-call runbook?

Each runbook should cover: what the alert means, how to verify the issue, immediate mitigation steps, escalation path, and links to relevant dashboards and logs. For Node.js services specifically, include how to capture a heap dump, how to profile CPU usage, how to check event loop lag, and how to roll back a deployment. Keep runbooks in version control next to the service code.

Principal Engineer

Q: When should you pick Node.js over Go, Rust, or Java?

Node.js excels at I/O-heavy workloads (APIs, real-time apps, BFFs) and when your team already knows JavaScript. Go is better for CPU-intensive services, CLI tools, and when you need simple concurrency with goroutines. Rust fits performance-critical systems where you need zero-cost abstractions and memory safety without a GC. Java is strong for large enterprise systems with mature ecosystems for transactions and messaging.

Q: How do you design event-driven architecture at scale?

Use Apache Kafka for high-throughput event streaming where ordering and replay matter. Use RabbitMQ or SQS for traditional task queues with routing and dead-letter support. Define a schema registry (Avro or Protobuf) to enforce event contracts across teams. Design events as facts (OrderPlaced) not commands (PlaceOrder). Plan for at-least-once delivery and make consumers idempotent.

Q: How do you choose between SQL, NoSQL, and NewSQL?

SQL (PostgreSQL, MySQL) is the default for structured data with relationships and transactions. NoSQL (MongoDB, DynamoDB) fits document-oriented data, high write throughput, or when your schema evolves rapidly. NewSQL (CockroachDB, TiDB) gives you SQL semantics with horizontal scalability. Pick based on your data model, consistency requirements, and scale. Most applications should start with PostgreSQL.

Q: How do you approach infrastructure-as-code for Node.js services?

Use Terraform or Pulumi for provisioning cloud resources (databases, queues, load balancers) and Docker plus Kubernetes manifests (or ECS task definitions) for service deployment. Every environment (dev, staging, prod) should be reproducible from code. Store infrastructure code alongside application code or in a shared platform repo. Use a GitOps workflow where merging to main triggers deployment.

Q: How do you optimize cost for serverless Node.js?

Reduce cold starts by keeping bundle size small (tree-shake, avoid heavy SDKs), using provisioned concurrency for critical paths, and choosing ARM (Graviton) runtimes for better price-performance. Set memory based on profiling, not guessing: Lambda CPU scales with memory allocation. Use reserved concurrency to prevent runaway scaling. Move high-throughput endpoints back to containers if the per-invocation cost exceeds a container equivalent.

Q: What does platform engineering look like for backend teams?

Build a self-service internal developer platform: service scaffolding (cookiecutter templates), CI/CD pipelines (reusable GitHub Actions or shared Jenkinsfiles), observability stack (tracing, metrics, logs pre-configured), and a service catalog (Backstage or similar). Your goal is to let product teams ship without filing infrastructure tickets. Measure success by time-to-first-deploy for a new service and mean time to recovery for incidents.

Contact