The http module and building a server

Intermediate · 30 min

How node:http turns bytes into req and res streams, routing and JSON handling by hand, and the keep-alive and timeout settings that matter.

Before thisBackpressure and highWaterMarkThe event loop phases

Hussein Nasser · 30 min

The http module and building a server

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Hussein NasserReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `http.createServer(handler)` calls `handler(req, res)` once per request. `req` is a Readable stream of the request body, and `res` is a Writable stream of the response.
  • The URL and method arrive as strings; routing is just branching on `req.method` and a parsed `new URL(req.url, base)`. Frameworks like Express add a nicer layer on top of exactly this.
  • Request bodies are streams, so read them with `for await (const chunk of req)` and enforce a size limit. Without one, a single client can exhaust memory.
  • Always set status and headers before `res.end()`, send `content-type` and ideally `content-length`, and handle thrown errors yourself, since a throw inside an async handler is an unhandled rejection.
  • Defaults worth knowing in current Node: `headersTimeout` 60 s, `requestTimeout` 300 s, `keepAliveTimeout` 5 s, and no socket idle timeout. Put a reverse proxy's keep-alive timeout above the server's.

What a server really is

An HTTP server is a loop: accept a TCP connection, parse the bytes into a request (method, path, headers, body), run your code, serialise a response. node:http does the first and last parts and hands you the middle.

import { createServer } from 'node:http';

createServer((req, res) => {
  res.end('hello');
}).listen(3000);

The handler runs once per request. req is an http.IncomingMessage, a Readable stream of the request body with method, url and headers attached. res is an http.ServerResponse, a Writable stream you write the body into. That is why backpressure and pipeline apply directly: await pipeline(createReadStream(file), res) serves a file without loading it.

Routing by hand

There is no router in node:http. You branch on the method and path. Parse the URL against a base, because req.url is only the path and query:

const server = createServer(async (req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  try {
    if (req.method === 'GET' && url.pathname === '/health') return send(res, 200, { ok: true });
    if (req.method === 'GET' && url.pathname === '/search') return send(res, 200, { q: url.searchParams.get('q') });
    const m = url.pathname.match(/^\/users\/(\d+)$/);
    if (m && req.method === 'GET') return send(res, 200, { id: Number(m[1]) });
    if (req.method === 'POST' && url.pathname === '/users') return send(res, 201, await readJson(req));
    send(res, 404, { error: 'not found' });
  } catch (err) {
    send(res, err.status ?? (err instanceof SyntaxError ? 400 : 500), { error: err.message });
  }
});

Everything here is the machinery that Express, Fastify and the rest build on. Notice the try/catch: an async handler that throws produces an unhandled rejection, and the client is left hanging. See uncaught errors.

Reading a body, writing a response

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

const send = (res, status, body) => {
  const data = JSON.stringify(body);
  res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) });
  res.end(data);
};

The size check is not optional. A body is untrusted input of any length, and without a limit one client can fill memory. I ran this server against fetch: /health returned { ok: true }, /users/42 returned { id: 42 }, a POST with {bad returned 400, and unknown paths returned 404.

Headers go out with the first write, so set the status and headers before the body. After end(), further writes fail with an ERR_STREAM_WRITE_AFTER_END error.

Keep-alive and timeouts

HTTP/1.1 reuses TCP connections between requests (keep-alive), because opening one costs a round trip or more. A server therefore holds idle connections open for a while. Node’s defaults on a fresh server on Node 26:

Setting Default Meaning
headersTimeout 60 s max time to receive the full request headers
requestTimeout 300 s max time to receive the entire request
keepAliveTimeout 5 s idle time before closing a keep-alive connection
server.timeout 0 socket inactivity timeout (0 means none)

The value to watch is keepAliveTimeout. Behind a load balancer or reverse proxy with a longer idle timeout, Node closes connections the proxy still thinks are open, and the next request on that connection fails as a reset. Set server.keepAliveTimeout higher than the proxy’s. On shutdown, server.close() stops accepting new connections but waits for existing ones, so follow it with server.closeIdleConnections() or closeAllConnections().

What the video covers

Hussein Nasser’s video from May 2022 is chaptered: the request object (0:30), request chaining (5:00), response.write (8:10), response.end (14:20), how Express middleware works (18:43), and a summary at 24:40. It uses the vanilla HTTP server, so it shows the req/res mechanics this lesson relies on and previews middleware, which the Express lesson picks up. It is a deep dive rather than a build-along, and I could not read a transcript. The routing helper, the body-size limit and the timeout table are from this page, run on Node 26. See HTTP basics for APIs for resource design.

Where this fits

Everything in the rest of this group sits on this: Express, Fastify and NestJS all wrap createServer. The client side is next: fetch and undici.

Check yourself

  1. 01Why does a handler read the request body with a loop over `req`?

    `req` is a Readable stream, so the body arrives in chunks that must be collected. `for await (const chunk of req)` gathers them, and checking the running size against a limit lets you reject oversized uploads with 413 before they fill memory.

  2. 02A client sends `{bad` as the body of a POST. What should the handler return, and what happens if it does not catch the error?

    It should return 400 with a message. `JSON.parse` throws a `SyntaxError`, and if the async handler does not catch it the rejection is unhandled, so the request hangs with no response and the process may crash depending on the unhandled-rejection mode.

  3. 03What does `res.writeHead(200, headers)` do compared with `res.write` and `res.end`?

    `writeHead` sets the status line and headers and queues them for sending. `write` sends body chunks, and `end` sends the final chunk and finishes the response. Calling `end` with no prior `writeHead` sends status 200 with default headers.

  4. 04Your Node server sits behind a load balancer with a 60 s idle timeout and clients sometimes see connection resets. A likely cause?

    Node's `keepAliveTimeout` defaults to 5 s, so it closes idle connections the balancer still thinks are open and the next request on that connection fails. Raise `server.keepAliveTimeout` above the balancer's idle timeout.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark