Menu

Build a tiny HTTP server

“Everything from this guide in about 35 lines of Node.js, with no libraries.”

View .md

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#

server.mjsjs
 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:

bash
node server.mjs

Talk to it#

Open a second terminal.

List todos (GET → 200):

bash
curl -i http://localhost:3000/todos
http
1HTTP/1.1 200 OK
2Content-Type: application/json
3
4[{"id":1,"title":"Learn HTTP","completed":false}]

Create one (POST + JSON body → 201):

bash
curl -i -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{"title": "Build a server"}'
http
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):

bash
curl -i -X POST http://localhost:3000/todos -d 'oops'

Ask for something that doesn’t exist (→ 404):

bash
curl -i http://localhost:3000/nope

What you just used#

Every piece of this guide shows up in those few lines:

Tip

Try next: add DELETE /todos/:id that answers 204 No Content, and PATCH /todos/:id to mark a todo as completed.

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. The server gets a POST /todos with the body oops. What does it answer?
  2. Which status does it send after creating a todo?
  3. Why does the send helper set Content-Type: application/json?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy