# Build a tiny HTTP server

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

Source: https://aminbytes.dev/bytes/http/hands-on/build-a-server/


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

```js {title="server.mjs"}
import { createServer } from "node:http";

const todos = [{ id: 1, title: "Learn HTTP", completed: false }];

const server = createServer(async (req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);
  console.log(req.method, url.pathname);

  // Small helper to send JSON with the right status and type
  const send = (status, data) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(data === undefined ? "" : JSON.stringify(data));
  };

  if (req.method === "GET" && url.pathname === "/todos") {
    return send(200, todos);
  }

  if (req.method === "POST" && url.pathname === "/todos") {
    let body = "";
    for await (const chunk of req) body += chunk;
    try {
      const { title } = JSON.parse(body);
      if (!title) return send(400, { error: "title is required" });
      const todo = { id: todos.length + 1, title, completed: false };
      todos.push(todo);
      return send(201, todo);
    } catch {
      return send(400, { error: "body must be JSON" });
    }
  }

  send(404, { error: "not found" });
});

server.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
HTTP/1.1 200 OK
Content-Type: application/json

[{"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
HTTP/1.1 201 Created
Content-Type: application/json

{"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:

- [URLs](../../basics/anatomy-of-a-url/): `new URL(req.url, …)` splits path and query
- [Methods](../../requests/http-methods/): `GET` reads, `POST` creates
- [Sending data](../../requests/sending-data/): the JSON body is read from the request stream
- [Status codes](../../responses/status-codes/): `200`, `201`, `400`, `404`
- [Content types](../../responses/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.


## Byte check

1. The server gets a `POST /todos` with the body `oops`. What does it answer?
   - `200 OK`
   - **`400 Bad Request`** (correct)
   - `500 Internal Server Error`
   `JSON.parse` fails, and the `catch` sends `400` with "body must be JSON".

2. Which status does it send after creating a todo?
   - `200`
   - **`201`** (correct)
   - `204`
   `201 Created` says something new exists now.

3. Why does the `send` helper set `Content-Type: application/json`?
   - **So the client knows how to read the body** (correct)
   - It makes the response faster
   - Node refuses to send without it
   Without it, the client has to guess what the bytes are.


