An HTTP server with node:http
A web server is a function that receives a request and writes a response, and node:http is the smallest way to put that function on a socket. The server object owns a port, calls the function once per request, and keeps the process alive until it is closed. There is no framework in this lesson: the routing, the status code and the body are all written by hand.
Every program listens on port zero and on 127.0.0.1, so the system picks a free port and nothing is reachable from another machine. The port number is never printed, because it changes with every run; the program prints facts about it instead. Each server is called from inside the same program and closed before the program ends, which is what makes the examples runnable on a page.
A server on port 0
createServer(handler) makes a server that is not listening yet. listen(0, '127.0.0.1') binds it, and the zero asks the operating system for any free port; server.address().port then reads the number that was chosen. The callback of listen runs once the port is open, and that is the moment a program may send its first request.
The program starts a server that answers every request with one line, calls it with fetch, prints the status and the body, and closes the server.
The file server.mjs:
import { createServer } from 'node:http';
const server = createServer((request, response) => {
console.log('the server saw:', request.method, request.url);
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('hello from the server\n');
});
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
console.log('the system picked a port above zero:', server.address().port > 0);
const answer = await fetch(`http://127.0.0.1:${server.address().port}/hello`);
console.log('the status:', answer.status);
console.log('the body:', JSON.stringify(await answer.text()));
await new Promise((resolve) => {
server.close(resolve);
});
console.log('the server is listening:', server.listening);
node server.mjs
the system picked a port above zero: true
the server saw: GET /hello
the status: 200
the body: "hello from the server\n"
the server is listening: false
The server saw a GET of /hello, and the response carried a status and a body. The last line is the important one for a program: after close the server is no longer listening, so nothing keeps the process alive.
Routes and status codes
A route is a comparison of request.url with a path, and a status code is the first line of the answer. Two hundred means the request was understood and the body is there, four hundred and four means the path does not exist, and the lesson on HTTP status codes lists the rest. The handler must end the response on every path, or the client waits forever.
The program serves a JSON health route and answers everything else with 404. It calls both routes from the same program and prints the status and the body of each answer.
The file routes.mjs:
import { createServer } from 'node:http';
const server = createServer((request, response) => {
if (request.url === '/health') {
response.writeHead(200, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ status: 'ok' }));
return;
}
response.writeHead(404, { 'Content-Type': 'text/plain' });
response.end('not found\n');
});
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const base = `http://127.0.0.1:${server.address().port}`;
for (const route of ['/health', '/missing']) {
const answer = await fetch(base + route);
console.log(route, 'answered', answer.status, await answer.text());
}
await new Promise((resolve) => {
server.close(resolve);
});
node routes.mjs
/health answered 200 {"status":"ok"}
/missing answered 404 not found
The two paths took two different branches of one function, and the status said which one before the body did. The body of the second answer ends with a newline of its own, which is why its log line is followed by an empty line on the terminal.
The request body
A request is a stream: the body arrives in chunks after the headers, and a handler reads it with for await or listens to its events. The program below joins the chunks into one string, parses it as JSON and answers with a status of 201, which says that something was created.
The program starts a server that echoes the parsed body, posts one note to it and prints the status and the reply. The handler also prints the raw body, so the page shows what the server received.
The file json.mjs:
import { createServer } from 'node:http';
const server = createServer(async (request, response) => {
let body = '';
for await (const chunk of request) {
body += chunk;
}
console.log('the request body:', body);
const data = body === '' ? null : JSON.parse(body);
response.writeHead(201, { 'Content-Type': 'application/json' });
response.end(JSON.stringify({ received: data }));
});
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const base = `http://127.0.0.1:${server.address().port}`;
const answer = await fetch(base + '/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'first note' }),
});
console.log('the status:', answer.status);
console.log('the reply:', JSON.stringify(await answer.json()));
await new Promise((resolve) => {
server.close(resolve);
});
node json.mjs
the request body: {"title":"first note"}
the status: 201
the reply: {"received":{"title":"first note"}}
The body arrived as a string of JSON and came back as part of a reply, and the status of the answer is 201 rather than 200 because the request created something. The request stream has no size limit of its own, which is why a server open to the network reads the content-length header and refuses a body above a limit it chose.
Closing the server
server.close(callback) stops accepting new connections and calls back when the open ones have ended. Until then the process stays alive, which is the reason a server program looks like it hangs: something is still listening. A request to a closed port fails at once with a connection refused, which is the same error a client gets from a service that is simply down.
The program calls its server once, closes it, and then calls it again to show the failure.
The file close.mjs:
import { createServer } from 'node:http';
const server = createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('still here\n');
});
await new Promise((resolve) => {
server.listen(0, '127.0.0.1', resolve);
});
const url = `http://127.0.0.1:${server.address().port}/`;
const first = await fetch(url);
console.log('before the close:', first.status);
await new Promise((resolve) => {
server.close(resolve);
});
console.log('the server is listening:', server.listening);
try {
await fetch(url);
} catch (error) {
console.log('after the close:', error.cause?.code ?? error.message);
}
node close.mjs
before the close: 200
the server is listening: false
after the close: ECONNREFUSED
The first answer was a normal 200 and the second never reached a server, so fetch rejected with a network error whose cause carries the code. That distinction is the subject of the next lesson: a client has to know which failures come from the network and which come from the answer.
Exercises
- Add a route that answers with a fixed JSON body. Why is a real clock a bad idea for the output of a page like this one?
- Answer a POST to the health route with 405. Which line of the handler changes?
- Send a body that is not JSON. What should the server answer, and which header tells the client so?
- Print the request headers on the server side. Which header carries the type of the body?
- Start two servers on port zero in one program. Do they get the same port, and what happens if you ask both for 8080?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does the lesson listen on port 0?
Answer
The system picks a free port, so two runs never collide
A fixed port would fail whenever something else on the machine already uses it.
-
What does this program print? ``
import { createServer } from "node:http"; const server = createServer((request, response) => { response.writeHead(200, { "Content-Type": "text/plain" }); response.end("ok"); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const answer = await fetch(http://127.0.0.1:${server.address().port}/); console.log(answer.status, await answer.text()); await new Promise((resolve) => server.close(resolve));``Answer
200 ok
The handler answers 200 with the body ok, and the client prints both.
-
What does writeHead(404) set?
Answer
The status code of the response
The number is the status, and the headers go in the second argument.
-
What does this program print? ``
import { createServer } from "node:http"; const server = createServer((request, response) => { response.writeHead(201, { "Content-Type": "text/plain" }); response.end("created"); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const answer = await fetch(http://127.0.0.1:${server.address().port}/); console.log(answer.status, answer.statusText); await new Promise((resolve) => server.close(resolve));``Answer
201 Created
The status text is the standard phrase that belongs to the code.
-
How does a handler read the body of a request?
Answer
By iterating the request stream
The request is a readable stream, and for await collects its pieces.
-
What does this program print? ``
import { createServer } from "node:http"; const server = createServer((request, response) => { response.end("ok"); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const url =http://127.0.0.1:${server.address().port}/; await new Promise((resolve) => server.close(resolve)); try { await fetch(url); } catch (error) { console.log(error.cause?.code ?? error.message); }``Answer
ECONNREFUSED
The port is closed, so the connection itself fails and fetch rejects.
-
What does server.close do?
Answer
It stops new connections and calls back when the open ones have ended
The callback is what lets a program wait for a clean end.
-
What does this program print? ``
import { createServer } from "node:http"; const server = createServer(async (request, response) => { let body = ""; for await (const chunk of request) { body += chunk; } response.end(String(body.length)); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const answer = await fetch(http://127.0.0.1:${server.address().port}/, { method: "POST", body: "abc", }); console.log(await answer.text()); await new Promise((resolve) => server.close(resolve));``Answer
3
The handler counted the three characters of the body and answered with the number.
-
Which address does the lesson bind?
Answer
127.0.0.1, so only this machine can reach the server
A lesson that opens no port to the network is safe to run anywhere.
-
Why does a server program keep running after the last line?
Answer
An open server keeps the event loop busy
A listening server is pending work, so the process ends only after close.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev