Script Valley
Node.js: The Complete Runtime
Node.js Core ModulesLesson 3.3

Building an HTTP server with Node.js http module

http.createServer, IncomingMessage, ServerResponse, request URL parsing, method routing, setting headers, status codes, sending JSON responses

http.createServer Is the Foundation

The built-in http module lets you create an HTTP server without any framework. Understanding it makes Express and Fastify much less magical.

const http = require('http');

const server = http.createServer((req, res) => {
  const { method, url } = req;

  if (method === 'GET' && url === '/') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ message: 'Hello World' }));
    return;
  }

  if (method === 'GET' && url === '/health') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('OK');
    return;
  }

  res.writeHead(404, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ error: 'Not found' }));
});

server.listen(3000, () => console.log('Running on :3000'));

Reading Request Body

let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', () => {
  const data = JSON.parse(body);
});

This raw approach works but is tedious. Express handles body parsing via middleware โ€” this is why it exists.

Up next

Node.js streams: reading and writing large data efficiently

Sign in to track progress

Building an HTTP server with Node.js http module โ€” Node.js Core Modules โ€” Node.js: The Complete Runtime โ€” Script Valley โ€” Script Valley