Menu
Build a tiny HTTP server
“Everything from this guide in about 35 lines of Node.js, with no libraries.”
Time to be the server. We’ll build a small to-do API using only Node’s built-in http module, then talk to it with curl.
The server#
1import { createServer } from "node:http";
2
3const todos = [{ id: 1, title: "Learn HTTP", completed: false }];
4
5const server = createServer(async (req, res) => {
6 const url = new URL(req.url, `http://${req.headers.host}`);
7 console.log(req.method, url.pathname);
8
9 // Small helper to send JSON with the right status and type
10 const send = (status, data) => {
11 res.writeHead(status, { "Content-Type": "application/json" });
12 res.end(data === undefined ? "" : JSON.stringify(data));
13 };
14
15 if (req.method === "GET" && url.pathname === "/todos") {
16 return send(200, todos);
17 }
18
19 if (req.method === "POST" && url.pathname === "/todos") {
20 let body = "";
21 for await (const chunk of req) body += chunk;
22 try {
23 const { title } = JSON.parse(body);
24 if (!title) return send(400, { error: "title is required" });
25 const todo = { id: todos.length + 1, title, completed: false };
26 todos.push(todo);
27 return send(201, todo);
28 } catch {
29 return send(400, { error: "body must be JSON" });
30 }
31 }
32
33 send(404, { error: "not found" });
34});
35
36server.listen(3000, () => console.log("Listening on http://localhost:3000"));Run it:
node server.mjsTalk to it#
Open a second terminal.
List todos (GET → 200):
curl -i http://localhost:3000/todos1HTTP/1.1 200 OK
2Content-Type: application/json
3
4[{"id":1,"title":"Learn HTTP","completed":false}]Create one (POST + JSON body → 201):
curl -i -X POST http://localhost:3000/todos \
-H "Content-Type: application/json" \
-d '{"title": "Build a server"}'1HTTP/1.1 201 Created
2Content-Type: application/json
3
4{"id":2,"title":"Build a server","completed":false}Send something wrong (bad JSON → 400):
curl -i -X POST http://localhost:3000/todos -d 'oops'Ask for something that doesn’t exist (→ 404):
curl -i http://localhost:3000/nopeWhat you just used#
Every piece of this guide shows up in those few lines:
- URLs:
new URL(req.url, …)splits path and query - Methods:
GETreads,POSTcreates - Sending data: the JSON body is read from the request stream
- Status codes:
200,201,400,404 - Content types:
Content-Type: application/json
Tip
Try next: add DELETE /todos/:id that answers 204 No Content, and PATCH /todos/:id to mark a todo as completed.
Answer these 3 questions to commit this byte to your learning path.
Reset. This byte isn't committed any more. Answer the questions again to commit it.
$ git commit -m "learn(http): Build a tiny HTTP server"
[main c11f168] learn(http): Build a tiny HTTP server
1 byte changed, 3 insertions(+)
See it on your path Already committed . Try the questions again any time, it won't undo anything. To uncommit it and start over: