Creating an HTTP Server
One of Node.js's most popular uses is building web servers. The built-in http module lets you create servers that handle web requests without any external dependencies. In this lesson, you'll create your first HTTP server.
The http Module
Node.js includes the http module for creating servers:
const http = require('http');
const server = http.createServer((request, response) => {
response.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
That's it! Just 7 lines to create a working web server.
Understanding the Request Handler
The function passed to createServer is called for every incoming request:
http.createServer((request, response) => {
// request (req) - Information about the incoming request
// response (res) - How you send data back to the client
});
The Request Object
const server = http.createServer((req, res) => {
console.log('Method:', req.method); // GET, POST, PUT, DELETE
console.log('URL:', req.url); // /path/to/resource
console.log('Headers:', req.headers); // { host: '...', ... }
console.log('HTTP Version:', req.httpVersion); // 1.1
res.end('Request received');
});
The Response Object
const server = http.createServer((req, res) => {
// Set status code
res.statusCode = 200;
// Set headers
res.setHeader('Content-Type', 'text/plain');
// Or set both at once
res.writeHead(200, { 'Content-Type': 'text/html' });
// Write body
res.write('Hello ');
res.write('World');
// End response (required!)
res.end('!');
});
Starting the Server
The listen() Method
// Listen on port 3000
server.listen(3000);
// With callback
server.listen(3000, () => {
console.log('Server started');
});
// Specify host and port
server.listen(3000, '127.0.0.1', () => {
console.log('Listening on 127.0.0.1:3000');
});
// Listen on all interfaces
server.listen(3000, '0.0.0.0', () => {
console.log('Available from network');
});
Choosing a Port
| Port Range | Description |
|---|---|
| 0-1023 | Well-known ports (requires admin) |
| 1024-49151 | Registered ports |
| 49152-65535 | Dynamic/private ports |
Common development ports: 3000, 8000, 8080, 5000
Complete Example: Hello World Server
const http = require('http');
const PORT = 3000;
const server = http.createServer((req, res) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
// Handle server errors
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
console.error(`Port ${PORT} is already in use`);
} else {
console.error('Server error:', err);
}
});
Returning HTML
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>My Node.js Server</title>
</head>
<body>
<h1>Welcome to Node.js!</h1>
<p>This page was served at ${new Date().toLocaleTimeString()}</p>
</body>
</html>
`);
});
server.listen(3000);
Returning JSON
For APIs, return JSON data:
const http = require('http');
const server = http.createServer((req, res) => {
const data = {
message: 'Hello from API',
timestamp: new Date().toISOString(),
version: '1.0.0'
};
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});
server.listen(3000);
Common Content Types
| Content-Type | Description |
|---|---|
text/plain | Plain text |
text/html | HTML document |
application/json | JSON data |
text/css | CSS stylesheet |
text/javascript | JavaScript code |
image/png | PNG image |
image/jpeg | JPEG image |
application/pdf | PDF document |
HTTP Status Codes
// Success
res.statusCode = 200; // OK
res.statusCode = 201; // Created
res.statusCode = 204; // No Content
// Redirect
res.statusCode = 301; // Moved Permanently
res.statusCode = 302; // Found (temporary redirect)
// Client Error
res.statusCode = 400; // Bad Request
res.statusCode = 401; // Unauthorized
res.statusCode = 403; // Forbidden
res.statusCode = 404; // Not Found
// Server Error
res.statusCode = 500; // Internal Server Error
res.statusCode = 503; // Service Unavailable
Stopping the Server
const server = http.createServer((req, res) => {
res.end('OK');
});
server.listen(3000);
// Graceful shutdown
process.on('SIGINT', () => {
console.log('Shutting down...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
// Or programmatically
setTimeout(() => {
server.close();
}, 60000); // Close after 60 seconds
Key Takeaways
- Use
http.createServer()to create a server - The callback receives
requestandresponseobjects - Always call
res.end()to complete the response - Set
Content-Typeheader to tell clients what you're sending - Use
server.listen(port)to start accepting connections - Handle the 'error' event for issues like port conflicts
- Use
server.close()for graceful shutdown
Summary
You've created your first HTTP server with Node.js! You understand the request/response cycle, how to set headers and status codes, and how to return different content types. This foundation will help you build more complex servers.
Next, you'll learn how to handle different types of requests and extract information from them.

