Skip to main content

The Server Calls You

A Node.js web server is built from handlers: functions with the shape (req: IncomingMessage, res: ServerResponse) => void, from the built-in node:http module. The server accepts connections and calls your handler once per request — req holds everything about the request, and whatever you write into res becomes the response.

A real server starts with server.listen(8080) and runs forever. The examples here call server.listen(0) instead: port 0 means "any free port", so nothing can collide. Each example then reads the real port, makes its own request with fetch, and calls server.close() — so every program runs and finishes by itself.


A First Handler

The smallest possible handler writes a line of text. Everything an API does — JSON, status codes, routing — happens inside this same function shape.

Hello from a handler

The handler writes into res; the client reads exactly that as the response body, with status 200 OK filled in automatically.

Prompt
Write a TypeScript program with the smallest possible node:http handler, one that writes a hello line. Serve it on port 0, send one GET request with fetch, print the response status and body, and close the server.
Output: TypeScript file and captured output

Answering with JSON

An API handler does three things: set the Content-Type header, choose a status code, and write the data. res.writeHead(200, { "Content-Type": "application/json" }) does the first two, and res.end(JSON.stringify(value)) writes the body.

Order matters: the status and the headers must be set before the body is written.

A JSON endpoint

The handler turns a UserRecord into JSON text and sends it. The client receives valid JSON and the right content type — this is the skeleton of every endpoint in the rest of this group.

Prompt
Write a TypeScript program with a handler that answers with a UserRecord as JSON, setting the status and the Content-Type header with res.writeHead. Serve it on port 0, request it with fetch and print the status, the content type and the JSON body.
Output: TypeScript file and captured output