Interview questionsNode.js
Node.js interview questions and answers
21 Node.js questions picked from Codejump's quizzes, from the basics a junior is expected to know to the details that trip up senior candidates. Each one comes with its answer and an explanation — try to answer before you open it.
Junior level Node.js questions
1.What is Express.js?
javascriptconst express = require("express"); const app = express(); // Middleware app.use(express.json()); // GET route app.get("/", (req, res) => { res.send("Hello, World!"); }); // POST route app.post("/api/users", (req, res) => { const user = req.body; res.json({ message: "User created", user }); }); // Start server app.listen(3000, () => { console.log("Server running on port 3000"); });- A.A real-time database system.
- B.A CSS framework.
- C.A front-end JavaScript library.
- D.A minimal and flexible Node.js web application framework.
Show answer
Answer: D. A minimal and flexible Node.js web application framework.
Express.js is a lightweight web framework for Node.js that simplifies building web applications and APIs. Example with Express: Express features:- Routing (GET, POST, PUT, DELETE)
- Middleware support
- Request/response handling
- Error handling
- Static file serving
From the quiz Core Modules & CLI
2.What are the common HTTP methods used in REST APIs?
javascript// GET - Retrieve app.get("/api/users", (req, res) => { res.json(users); }); // POST - Create app.post("/api/users", (req, res) => { users.push(req.body); res.json({ message: "User created" }); }); // PUT - Replace app.put("/api/users/:id", (req, res) => { users[id] = req.body; res.json({ message: "User replaced" }); }); // PATCH - Update partial app.patch("/api/users/:id", (req, res) => { users[id] = { ...users[id], ...req.body }; res.json({ message: "User updated" }); }); // DELETE - Remove app.delete("/api/users/:id", (req, res) => { delete users[id]; res.json({ message: "User deleted" }); });- A.GET, POST, UPDATE, DELETE
- B.READ, WRITE, MODIFY, REMOVE
- C.FETCH, SEND, CHANGE, ERASE
- D.GET, POST, PUT/PATCH, DELETE
Show answer
Answer: D. GET, POST, PUT/PATCH, DELETE
HTTP methods define what action to perform on a resource: | Method | Purpose | Example | |--------|---------|---------| | GET | Retrieve data |GET /api/users- Get all users | | POST | Create new data |POST /api/users- Create user | | PUT | Replace entire resource |PUT /api/users/1- Replace user 1 | | PATCH | Partial update |PATCH /api/users/1- Update user 1 field | | DELETE | Remove data |DELETE /api/users/1- Delete user 1 | Example with Express:From the quiz Core Modules & CLI
3.What does this Express route do?
javascriptapp.get("/api/users/:id", (req, res) => { const id = req.params.id; res.json({ id: id, name: "User " + id }); });- A.Handles POST requests to create a user.
- B.Handles DELETE requests.
- C.Handles all requests to /api/users.
- D.Handles GET requests to retrieve a specific user by ID.
Show answer
Answer: D. Handles GET requests to retrieve a specific user by ID.
This route handles GET requests to/api/users/:idwhere:idis a URL parameter. How it works: URL parameters vs Query strings:From the quiz Core Modules & CLI
4.What is middleware in Express?
javascriptconst express = require("express"); const app = express(); // Middleware 1: Parse JSON app.use(express.json()); // Middleware 2: Logging app.use((req, res, next) => { console.log(`${req.method} ${req.path}`); next(); // Pass control to next middleware }); // Middleware 3: Authentication app.use((req, res, next) => { if (!req.headers.authorization) { return res.status(401).json({ error: "Unauthorized" }); } next(); }); // Route handler app.get("/api/users", (req, res) => { res.json({ users: [] }); });- A.A function that runs before the route handler to process request/response.
- B.A function that runs between database and application.
- C.A database layer.
- D.A security feature.
Show answer
Answer: A. A function that runs before the route handler to process request/response.
Middleware functions execute before route handlers to process requests or responses. Example of middleware: Execution flow: Key point: Callnext()to pass control to the next middleware.From the quiz Core Modules & CLI
5.How do you handle JSON data in Express?
javascriptconst express = require("express"); const app = express(); // Enable JSON parsing middleware app.use(express.json()); app.post("/api/users", (req, res) => { console.log(req.body); // Parsed JSON is automatically available const user = { name: req.body.name, email: req.body.email }; res.json({ message: "User created", user }); }); app.listen(3000);- A.Use express.json() middleware to automatically parse JSON.
- B.Use fs.readFile() manually for each request.
- C.JSON cannot be handled in Node.js.
- D.Use the json package from npm.
Show answer
Answer: A. Use express.json() middleware to automatically parse JSON.
Express provides built-inexpress.json()middleware that automatically parses incoming JSON requests. Using express.json(): Without middleware (manual parsing): With middleware (proper way):From the quiz Core Modules & CLI
6.What is the purpose of a database in a backend application?
javascriptlet users = []; // In-memory, lost on restart app.post("/api/users", (req, res) => { users.push(req.body); // Stored in memory only res.json({ message: "User created" }); }); app.get("/api/users", (req, res) => { res.json(users); // Empty after app restarts });- A.To store HTML files.
- B.To persist data that survives application restarts.
- C.To cache CSS files.
- D.To display web pages.
Show answer
Answer: B. To persist data that survives application restarts.
A database stores data persistently, so it survives even when the application stops and restarts. Without database (data lost on restart): With database (data persists): Common databases for Node.js:- SQL: PostgreSQL, MySQL
- NoSQL: MongoDB, Firebase
From the quiz Core Modules & CLI
7.What are the core principles of a REST API?
javascript// Good RESTful URLs GET /api/users // Get all users GET /api/users/5 // Get user 5 POST /api/users // Create user PUT /api/users/5 // Update user 5 DELETE /api/users/5 // Delete user 5 // Bad (non-RESTful) GET /api/getAllUsers GET /api/getUser/5 GET /api/createUser GET /api/deleteUser/5- A.Random endpoint structure and any response format.
- B.All endpoints should be at /api.
- C.Standard HTTP methods, resource-based URLs, and structured responses.
- D.REST APIs don't exist.
Show answer
Answer: C. Standard HTTP methods, resource-based URLs, and structured responses.
REST (Representational State Transfer) APIs follow standard conventions: Principles: 1. Resource-based URLs (nouns, not verbs) 2. Standard HTTP methods- GET for retrieving
- POST for creating
- PUT/PATCH for updating
- DELETE for removing 3. Structured responses 4. Consistent status codes
- 200 OK
- 201 Created
- 400 Bad Request
- 401 Unauthorized
- 404 Not Found
- 500 Server Error
From the quiz Core Modules & CLI
Mid level Node.js questions
8.What is a database connection pool?
javascript// Each request creates a new connection (expensive) app.get("/api/users", async (req, res) => { const conn = await createDatabaseConnection(); // SLOW const users = await conn.query("SELECT * FROM users"); await conn.close(); // SLOW res.json(users); });- A.A pool of water for databases.
- B.Multiple databases working together.
- C.Reusing database connections to avoid overhead of creating new ones.
- D.A backup for database failures.
Show answer
Answer: C. Reusing database connections to avoid overhead of creating new ones.
A connection pool maintains a set of reusable database connections. Reusing connections is faster than creating new ones for each request. Without connection pooling (slow): With connection pooling (fast): Connection pool workflow:From the quiz HTTP Servers & APIs
9.Why is validating user input important?
javascriptapp.post("/api/users", (req, res) => { // No validation! const user = { name: req.body.name, // Could be null, empty, or have SQL injection email: req.body.email, // Could be invalid format age: req.body.age // Could be negative or "not a number" }; db.insertUser(user); // Inserts bad data res.json({ message: "User created" }); }); // User sends: { name: "", email: "invalid", age: -5 } // Bad data enters database- A.Prevent invalid/malicious data from entering the system.
- B.Validation is not necessary.
- C.Make the code run faster.
- D.Validation is only for frontend.
Show answer
Answer: A. Prevent invalid/malicious data from entering the system.
Input validation prevents invalid data, security issues, and data corruption. Example of unvalidated input (vulnerable): Example with validation: Benefits:- Prevent invalid data
- Protect against SQL injection
- Improve data quality
- Better error messages
From the quiz HTTP Servers & APIs
10.What is the difference between authentication and authorization?
javascriptAuthentication: Login with username/password → Server verifies identity Authorization: User ID 5 is accessing /api/admin → Server checks if user 5 is admin Authentication: "Are you Alice?" Authorization: "Can Alice access the admin panel?"- A.Authentication verifies identity; authorization checks permissions.
- B.They are the same thing.
- C.Authorization is only for frontend.
- D.Authentication is not needed.
Show answer
Answer: A. Authentication verifies identity; authorization checks permissions.
- Authentication: Verifies who you are (login)
- Authorization: Checks what you can do (permissions) Example: Example implementation:
From the quiz HTTP Servers & APIs
11.What is the benefit of streaming large files instead of loading into memory?
javascriptapp.get("/download/file", (req, res) => { // Entire 1GB file loaded into memory! const fileContent = fs.readFileSync("large-file.bin"); res.send(fileContent); // Huge memory spike });- A.No benefit; streaming is slower.
- B.Memory is unlimited.
- C.Streaming is only for videos.
- D.Reduces memory usage by processing data in chunks.
Show answer
Answer: D. Reduces memory usage by processing data in chunks.
Streaming processes data in chunks instead of loading everything into memory. Essential for large files. Without streaming (loads entire file in memory): With streaming (memory-efficient): How streaming works: Use cases:- Video streaming
- Large file downloads
- Database query results
- Real-time data (logs, metrics)
From the quiz HTTP Servers & APIs
12.What does CORS do?
javascriptFrontend at: http://localhost:3000 API at: http://localhost:4000 Browser blocks request (different origins) ❌ Error: "No 'Access-Control-Allow-Origin' header"- A.Compresses data.
- B.Allows or restricts requests from different domains.
- C.Encrypts data transmission.
- D.Manages database connections.
Show answer
Answer: B. Allows or restricts requests from different domains.
CORS (Cross-Origin Resource Sharing) is a security mechanism that controls which domains can access your API. CORS problem: Solution: Enable CORS: How CORS works: CORS headers:From the quiz HTTP Servers & APIs
13.Why use clustering in Node.js?
javascriptCPU 1: 100% (Node.js process) CPU 2: 0% (unused) CPU 3: 0% (unused) CPU 4: 0% (unused) Performance: 25% of total capacity- A.Clustering allows running multiple processes to utilize multiple CPU cores.
- B.Clustering is for organizing code.
- C.Clustering is not useful in Node.js.
- D.Clustering is only for databases.
Show answer
Answer: A. Clustering allows running multiple processes to utilize multiple CPU cores.
Node.js runs on a single thread. Clustering lets you spawn multiple processes to use all CPU cores. Without clustering (single core): With clustering (all cores): CPU utilization with clustering:From the quiz HTTP Servers & APIs
14.Which strategies help scale Node.js applications?
javascript┌─────────┐ │Load │ │Balancer │ └────┬────┘ ┌────┴────┐ ┌─────┴─┐ ┌────┴─────┐ ┌───┴──┐ ┌──┴──┐ ┌─────┐ │Server│ │Server│ │Server│ └──────┘ └──────┘ └─────┘- A.Using more powerful hardware only.
- B.Scaling is not needed; Node.js is infinitely scalable.
- C.Horizontal scaling (multiple servers), caching, load balancing, database optimization.
- D.Vertical scaling is the only option.
Show answer
Answer: C. Horizontal scaling (multiple servers), caching, load balancing, database optimization.
Scaling involves multiple strategies working together: Strategies: 1. Horizontal Scaling: Multiple servers 2. Caching: Store frequently accessed data 3. Load Balancing: Distribute traffic 4. Database Optimization:- Indexing
- Query optimization
- Connection pooling
- Read replicas 5. Vertical Scaling: More powerful hardware (limited benefit) Combined approach:
From the quiz HTTP Servers & APIs
Senior level Node.js questions
15.What's wrong with this stream code?
javascriptapp.get("/download", (req, res) => { const stream = fs.createReadStream("large-file.bin"); stream.pipe(res); // No error handling });- A.No problem; streams handle errors automatically.
- B.Errors are not caught; connection might hang or crash.
- C.Piping is deprecated.
- D.Only happens with large files.
Show answer
Answer: B. Errors are not caught; connection might hang or crash.
Streams without error handlers can cause unhandled errors and hung connections. Errors that might occur: Without error handling (bad): With error handling (good): Better approach with pipeline:From the quiz Streams & Performance
16.What does graceful shutdown mean?
javascript// Client loses response mid-stream process.exit(0); // Kills immediately- A.Immediately kill all connections.
- B.Always use SIGKILL.
- C.Shutdown is irrelevant in Node.js.
- D.Complete in-flight requests before shutting down server.
Show answer
Answer: D. Complete in-flight requests before shutting down server.
Graceful shutdown completes current requests before closing the server, preventing data loss and client errors. Bad: Immediate shutdown (connection drops): Good: Graceful shutdown: Graceful shutdown flow: With timeout (fallback):From the quiz Streams & Performance
17.What memory leak might occur here?
javascriptapp.post("/setup-monitor", (req, res) => { const userId = req.body.userId; // Create interval that never stops setInterval(() => { console.log(`Monitoring user ${userId}`); }, 1000); res.json({ message: "Monitoring started" }); });- A.No problem; timers are cleaned up automatically.
- B.Timers are stored in database, causing DB bloat.
- C.Memory leak: timers keep piling up with each request.
- D.Only happens with many requests.
Show answer
Answer: C. Memory leak: timers keep piling up with each request.
Each POST request creates a new interval that never stops. After 1000 requests, 1000 intervals run every second. Memory leak scenario: Solution: Store interval ID and clear on shutdownFrom the quiz Streams & Performance
18.What is HTTP/2 Server Push and when is it useful?
javascriptBrowser requests index.html Server sends index.html Browser parses HTML Browser sees <link href="style.css"> Browser requests style.css Server sends style.css Browser renders page- A.Pushing data to clients forcefully.
- B.Server proactively sends resources client will need, reducing round trips.
- C.HTTP/2 is deprecated.
- D.Server Push only works for images.
Show answer
Answer: B. Server proactively sends resources client will need, reducing round trips.
Server Push allows the server to send resources to the client proactively, before the client requests them. This reduces latency. Traditional request (HTTP/1.1): With Server Push (HTTP/2): Implementing Server Push: Benefits:- Reduced round trips
- Faster page load
- Better performance
From the quiz Streams & Performance
19.What is a reverse proxy and why use it?
javascriptClient → Reverse Proxy (Nginx) → App Server 1 → App Server 2 → App Server 3- A.Server that sits in front of app servers, handling requests before forwarding.
- B.Proxy that clients connect to.
- C.Proxy for reverse engineering.
- D.Used only in development.
Show answer
Answer: A. Server that sits in front of app servers, handling requests before forwarding.
A reverse proxy forwards client requests to backend servers, providing load balancing, caching, and security benefits. Architecture with reverse proxy: Nginx reverse proxy configuration: Benefits:- Load balancing: Distribute traffic
- Caching: Cache responses
- SSL termination: Handle HTTPS
- Compression: Reduce payload size
- Security: Hide backend servers
- Rate limiting: Prevent abuse Node.js reverse proxy:
From the quiz Streams & Performance
20.What metrics should you monitor in a Node.js application?
javascript// CPU usage console.log(process.cpuUsage()); // { user: 12345, system: 6789 } // Memory usage console.log(process.memoryUsage()); // { rss: 50MB, heapTotal: 40MB, heapUsed: 30MB, external: 1MB } // Request latency const start = Date.now(); res.on("finish", () => { const duration = Date.now() - start; console.log(`Request took ${duration}ms`); }); // Error rate app.use((err, req, res, next) => { metrics.increment("errors"); }); // Database queries db.on("query", (query) => { metrics.recordQueryTime(query.time); });- A.No monitoring needed.
- B.Monitoring is only for enterprise apps.
- C.Only errors.
- D.CPU, memory, request latency, error rate, database queries.
Show answer
Answer: D. CPU, memory, request latency, error rate, database queries.
Effective monitoring tracks performance metrics and helps identify issues. Key metrics: Using monitoring tools: Alerts to set up:- CPU > 80%
- Memory > 90%
- Request latency > 1000ms
- Error rate > 1%
- Database queries > 5000ms
From the quiz Streams & Performance
21.What caching strategies are effective in Node.js?
javascriptconst cache = new Map(); app.get("/api/users/:id", (req, res) => { const id = req.params.id; if (cache.has(id)) { return res.json(cache.get(id)); } const user = db.getUser(id); cache.set(id, user); // Cache for 1 minute setTimeout(() => cache.delete(id), 60000); res.json(user); });- A.In-memory cache, Redis, HTTP caching headers, database query caching.
- B.No caching; always fetch fresh data.
- C.Caching always improves performance.
- D.Only cache static files.
Show answer
Answer: A. In-memory cache, Redis, HTTP caching headers, database query caching.
Multiple caching layers improve performance at different levels. 1. In-memory cache: 2. Redis distributed cache: 3. HTTP caching headers: 4. Database query caching: Cache invalidation (important!):From the quiz Streams & Performance
Practise 50+ more Node.js questions
Timed quizzes with instant feedback, the questions you miss coming back until they stick, coding challenges and AI mock interviews — free to start.