Building an HTTP server

Topic 2 of 4 in HTTP from scratch7 min readIntermediateFree course

Overview

Before using a framework, it’s worth building a server with nothing but Node’s built-in http module. It’s only a few lines, and it shows you exactly what every Node framework — Express, Fastify, Koa, Hono — does underneath. When something odd happens in Express later, you’ll know where to look.

Hello, server

JavaScript
// server.js
import http from 'node:http';

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain; charset=utf-8');
  res.end('Hello from Node!');
});

server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});
Terminal
node --watch server.js
curl -i http://localhost:3000

The -i flag makes curl show the response status and headers too. You can also open the address in a browser.

What happens on each request

A client sends GET /hello over TCP to your Node process. The server emits a ‘request’ event with req, an IncomingMessage readable stream holding the method, URL, headers and body chunks, and res, a ServerResponse writable stream with statusCode, setHeader, write and end. Calling res.end sends the response back to the client.

createServer returns a server (an EventEmitter). For every incoming request it calls your function with two objects:

  • req — an IncomingMessage. A readable stream of the request body, plus req.method, req.url and req.headers.
  • res — a ServerResponse. A writable stream for the response, plus methods to set the status and headers.

server.listen(3000) starts accepting connections on port 3000. The process now stays alive, waiting for requests, until you stop it.

Reading the request

JavaScript
const server = http.createServer((req, res) => {
  console.log(req.method);                   // 'GET'
  console.log(req.url);                      // '/courses?level=beginner' — path + query
  console.log(req.headers['user-agent']);    // header names are lower-case

  const url = new URL(req.url, `http://${req.headers.host}`);
  console.log(url.pathname);                 // '/courses'
  console.log(url.searchParams.get('level')); // 'beginner'
  res.end();
});

req.url is only the path and query, so turn it into a full URL object (with any base) to use pathname and searchParams.

Sending the response

JavaScript
res.statusCode = 201;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Location', '/courses/42');
res.end(JSON.stringify({ id: 42 }));

Or set the status and headers in one call:

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

The rules:

  • Set the status and headers before writing the body — once body bytes have been sent, headers can’t change (ERR_HTTP_HEADERS_SENT).
  • Call res.end() exactly once. Forget it, and the client waits until it times out. Call it twice, and you get an error.
  • res.write(chunk) can send the body in pieces before end() — that’s streaming.

A JSON helper

You’ll send JSON constantly, so wrap it:

JavaScript
function sendJson(res, status, data) {
  const body = JSON.stringify(data);
  res.writeHead(status, {
    'Content-Type': 'application/json; charset=utf-8',
    'Content-Length': Buffer.byteLength(body),
  });
  res.end(body);
}

Content-Length uses Buffer.byteLength, not body.length — remember from Buffers and encoding that characters and bytes differ.

Reading the request body

The body arrives as a stream of chunks, because it might be large. For a JSON body:

JavaScript
import { json } from 'node:stream/consumers';

if (req.method === 'POST') {
  try {
    const data = await json(req);
    sendJson(res, 201, { received: data });
  } catch {
    sendJson(res, 400, { error: 'Invalid JSON' });
  }
}

Always limit the size

Without a limit, someone can send a 10 GB body and fill your server’s memory. A small, careful reader:

JavaScript
async function readJson(req, limit = 1_000_000) {
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > limit) {
      const err = new Error('Body too large');
      err.status = 413;
      throw err;
    }
    chunks.push(chunk);
  }
  return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}

Express’s express.json() does exactly this for you (with a 100 KB default limit).

Serving a file

Because res is a writable stream, serving a file is a pipeline:

JavaScript
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

if (req.url === '/') {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  await pipeline(createReadStream(new URL('./public/index.html', import.meta.url)), res);
}

Handling errors

An exception inside the handler shouldn’t crash the server or leave the client hanging. Wrap the handler:

JavaScript
const server = http.createServer(async (req, res) => {
  try {
    await handle(req, res);
  } catch (err) {
    console.error(err);
    if (!res.headersSent) sendJson(res, err.status ?? 500, { error: 'Something went wrong' });
    else res.destroy();
  }
});

server.on('error', (err) => {
  if (err.code === 'EADDRINUSE') {
    console.error('Port 3000 is already in use — is another copy running?');
    process.exit(1);
  }
  throw err;
});

Ports and addresses

  • Ports below 1024 need administrator rights on most systems; use 3000, 8080 and so on in development.
  • server.listen(3000) accepts connections on every network interface. server.listen(3000, '127.0.0.1') only accepts them from the same machine.
  • Read the port from the environment — hosting platforms tell you which one to use: server.listen(Number(process.env.PORT ?? 3000)).

Why use a framework, then?

You’ve just written a working server — so why Express? Look at what you had to do by hand: parse URLs, match methods and paths, read and limit bodies, set JSON headers, catch errors. In a real API, with dozens of routes and shared logic like authentication, that repetition becomes the bulk of your code. Frameworks provide those pieces, tested and consistent. The next topic builds a router by hand so you see the last missing piece before switching to Express.

Remember: whatever framework you use, there’s always a req stream coming in and a res stream going out. Everything else is convenience.

Exercise

A JSON echo server

Build a server on port 3000. GET /health returns { "status": "ok" }. POST /echo reads a JSON body and returns it with an added receivedAt timestamp. Invalid JSON should get a 400 response; anything else a 404.

JavaScript
import http from 'node:http';

const server = http.createServer(async (req, res) => {
  // your code here
});

server.listen(3000);

Summary

  • http.createServer(handler) calls your handler for every request with req and res.
  • req is a readable stream with method, url and headers; res is a writable stream.
  • Set the status and headers, then send the body with res.end() — exactly once per request.
  • Read request bodies by consuming the req stream, and enforce a size limit.
  • Knowing the raw API explains what frameworks like Express do for you.