Courses / Node.js
1. Creating an http.Server with Node.js
Instantiate and start a basic HTTP server using Node's http.createServer and server.listen.
How It Works
Think of createServer as hiring a receptionist (a callback) who answers every incoming visitor (HTTP request); listen opens the shop door on a given port so visitors can arrive.
Call require('http').createServer(handler) to get a Server instance.
The handler runs for every incoming request and receives req and res objects to read and write HTTP data.
Call server.listen(port[, host]) to bind to a port so the OS routes TCP connections to your handler.
Use res.writeHead/statusCode and res.end to send headers and a response body, and close the response.
See It
This creates a server whose callback always returns a 200 plain-text response; server.listen binds port 3000 and the callback logs when listening; try changing the statusCode to 404 and request the URL to see the client receive a 404.
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello from Node HTTP server\n');
});
server.listen(3000, () => {
console.log('Server listening on http://localhost:3000/');
});Use It
Handle incoming webhook POST requests from a third-party service and reply quickly with 200 OK.
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/webhook') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
console.log('Webhook payload:', body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: true }));
});
} else {
res.writeHead(404);
res.end('Not found');
}
});
server.listen(8080);A plain http.Server is minimal, fast, and avoids extra dependencies when you only need simple request/response handling like webhooks.
Break It
What will a client receive when requesting this server?
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end({ ok: true }); // send an object directly
});
server.listen(3000, () => console.log('Listening'));res.end coerces a non-string, non-Buffer value to a string using default JavaScript ToString, so an object becomes "[object Object]" rather than JSON; Node does not automatically JSON.stringify objects for you.
Convert the object to a JSON string before sending, e.g. res.end(JSON.stringify({ ok: true }));
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ ok: true }));
});
server.listen(3000, () => console.log('Listening'));Level Up
Piping streams to the response: Pipe readable streams (file, child process) into res to stream large responses efficiently without buffering everything in memory.
Using http.Server with TLS via https.createServer: Swap to https.createServer with key/cert to serve over TLS while reusing the same request handler shape.
Graceful shutdown with server.close and connection tracking: Track open sockets and call server.close plus destroy long-lived connections to ensure clean shutdowns without dropped requests.
Prove It
Create a server that responds to GET /time with a JSON object { "time": "<ISO timestamp>" } and 404 for other paths.
JavaScript
Creating an http.Server with Node.js
A simple Node.js HTTP server listens for requests and sends back responses over TCP.
"I need a tiny server to handle webhooks and return JSON without a full framework."
Use Node's built-in http.createServer to make a server object that handles incoming requests; call server.listen to accept connections on a port.
"I need a tiny server to handle webhooks and return JSON without a full framework."
Use Node's built-in http.createServer to make a server object that handles incoming requests; call server.listen to accept connections on a port.