How Do You Create an HTTP Server in Node.js?
Build an HTTP server in Node.js with the built-in http module. Learn createServer, req and res, status codes, and routing with clear code examples.
Expected Interview Answer
You create an HTTP server in Node.js with the built-in http module by calling http.createServer() and passing a request handler, then calling server.listen(port) to start accepting connections.
The handler receives two objects on every request: req (an IncomingMessage with the URL, method, and headers) and res (a ServerResponse you write the reply into). You set a status code and headers with res.writeHead(), send the body with res.write() or res.end(), and finish the response with res.end(). Because Node.js is single-threaded and event-driven, one server process can handle thousands of concurrent connections without spawning a thread per request. Frameworks like Express wrap this same http module to add routing and middleware.
- Uses the built-in http module — no dependencies required
- Event-driven model handles many connections concurrently
- Full control over status codes, headers, and body
- Foundation that frameworks like Express build upon
- Runs cross-platform anywhere Node.js runs
AI Mentor Explanation
Creating an HTTP server is like appointing an umpire who stands ready at the pitch for every appeal. createServer defines how the umpire responds, and listen(port) tells him which ground to stand at. Each request is a fielding side's appeal; the umpire reads it, decides, and signals a response — out or not out — then resets instantly for the next ball without ever leaving the field.
Step-by-Step Explanation
Step 1
Import the http module
Load the built-in module with require('http') — no installation is needed.
Step 2
Create the server
Call http.createServer((req, res) => { ... }) and put your request-handling logic in the callback.
Step 3
Read the request
Inspect req.url and req.method to decide what to return for each route.
Step 4
Send the response
Use res.writeHead(status, headers) to set the status and headers, then res.end(body) to send the reply.
Step 5
Start listening
Call server.listen(port, callback) so the server binds to a port and starts accepting connections.
What Interviewer Expects
- Knowing http.createServer and server.listen
- Understanding the req and res objects
- Setting status codes and headers correctly
- Awareness that Express wraps the http module
- Why the event loop handles many connections at once
Common Mistakes
- Forgetting to call res.end(), leaving the request hanging
- Not setting a Content-Type header before sending the body
- Confusing req (incoming) with res (outgoing)
- Blocking the handler with synchronous heavy work
- Hardcoding a port instead of reading process.env.PORT
Best Answer (HR Friendly)
“In Node.js you create a web server with the built-in http module: you call createServer with a function that decides how to reply to each request, then tell it which port to listen on. From then on it answers every incoming request automatically.”
Code Example
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js!');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'ok', time: Date.now() }));
}).listen(3000);Follow-up Questions
- How does Express simplify creating an HTTP server?
- What is the difference between the req and res objects?
- How would you handle different routes without a framework?
- How do you read the body of a POST request in raw Node.js?
- What happens if you never call res.end()?
MCQ Practice
1. Which method starts the server listening for connections?
server.listen(port) binds the server to a port and begins accepting incoming connections.
2. What does the second argument (res) in the createServer callback represent?
res is the ServerResponse object you write status, headers, and body into to reply to the client.
3. Which module is required to build a basic HTTP server without any dependencies?
The built-in http module provides createServer and is all you need for a dependency-free server.
Flash Cards
Which method creates an HTTP server? — http.createServer(handler), where handler receives (req, res) for each request.
What ends and sends a response? — res.end(body) finishes the response; res.writeHead sets the status and headers first.
What are req and res? — req is the incoming request (IncomingMessage); res is the outgoing response (ServerResponse).
How does Express relate to http? — Express is a framework built on top of the http module, adding routing and middleware.