Tutorials / Modern JavaScript: Async, Modules and the Browser / A tiny HTTP server with Node.js

A tiny HTTP server with Node.js

16 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

What a server does

A web server waits for requests, and sends a response for each one. A request has a method (GET, POST, ...), a URL and headers. A response has a status code, headers and a body. Node can do this with no packages, using the built-in node:http module. Later you will probably use a framework such as Express or Fastify, and they are built on exactly what you learn here.

The smallest server

import http from "node:http";

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello from Node");
});

server.listen(3000, () => {
  console.log("Listening on http://localhost:3000");
});

createServer takes a function that Node calls for every request. It receives req (the request) and res (the response). We set a status and a header, then res.end sends the body and finishes. listen starts the server on a port. Run it, and open the address in a browser.

A server with routes and JSON

A real API looks at the method and the URL. Here is a small to-do API that stores items in memory. It also tests itself, so you can run the whole file and watch it work.

import http from "node:http";

const todos = [{ id: 1, text: "Learn Node", done: false }];

function sendJson(res, status, data) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data));
}

function readBody(req) {
  return new Promise((resolve, reject) => {
    let body = "";
    req.on("data", chunk => (body += chunk));
    req.on("end", () => {
      try {
        resolve(body ? JSON.parse(body) : {});
      } catch {
        reject(new Error("Invalid JSON"));
      }
    });
    req.on("error", reject);
  });
}

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");

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

    if (req.method === "POST" && url.pathname === "/todos") {
      const data = await readBody(req);
      if (!data.text) return sendJson(res, 400, { error: "text is required" });
      const todo = { id: Date.now(), text: data.text, done: false };
      todos.push(todo);
      return sendJson(res, 201, todo);
    }

    sendJson(res, 404, { error: "Not found" });
  } catch (error) {
    sendJson(res, 400, { error: error.message });
  }
});

server.listen(0, async () => {            // port 0 means "pick a free port"
  const base = `http://localhost:${server.address().port}`;

  let response = await fetch(`${base}/todos`);
  console.log(response.status, await response.json());

  response = await fetch(`${base}/todos`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text: "Build an API" }),
  });
  console.log(response.status, await response.json());

  response = await fetch(`${base}/todos`, { method: "POST", body: "{}" });
  console.log(response.status, await response.json());

  response = await fetch(`${base}/nothing`);
  console.log(response.status, await response.json());

  server.close();
});

Let me explain the pieces.

**sendJson** is a helper that sets the right status and Content-Type and stringifies the data. I always make a helper like this, so that every route responds in the same way.

**readBody** collects the request body. The body arrives in chunks, as data events. When the end event fires, we have it all, so we parse it. We wrap this in a promise so that handlers can await it, which ties in with the async lessons.

The handler checks req.method and url.pathname. For GET /todos it returns the list. For POST /todos it validates the data, adds a todo and replies 201 Created. Anything else gets 404. Invalid JSON is caught and answered with 400 Bad Request.

The test at the end starts the server on a free port, calls it using fetch (which exists in Node 18 and later), prints the results and closes the server. Note that the 400 case sends "{}", which has no text.

Status codes you will use

CodeWhen
200OK
201Created something
204OK with no body
400The client sent something invalid
404No such route or item
500A bug in your server

Choosing the right code lets clients react correctly, since the first thing they check is response.ok.

Serving a static file

import { readFile } from "node:fs/promises";

// inside the request handler
if (url.pathname === "/") {
  const html = await readFile("index.html", "utf8");
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  return res.end(html);
}

Be careful when serving files based on the URL. A path like /../../secret.txt can escape your folder if you join it blindly. That is called path traversal, and it is a classic security hole. Serve only files you list by name, or use a well-tested static file package.

When to use a framework

The raw http module is great for learning and for tiny services. As soon as you need routing with parameters like /todos/:id, middleware, body parsing, validation and authentication, a framework saves you real time and avoids many mistakes. Express is the most widely used, and Fastify and Hono are modern alternatives.

Common mistakes

  • **Forgetting res.end().** The browser waits forever.
  • Sending two responses. Calling res.end twice, or writing headers after the body started, throws an error. Use return after you respond.
  • **Not setting Content-Type.** The client may not parse your JSON.
  • Trusting the request body. Validate every field.
  • Crashing on bad JSON. JSON.parse throws, so catch it.
  • Hard-coding the port. Read process.env.PORT so the server works in hosting environments.

Try it yourself

  1. Run the example and open the /todos address in a browser while a longer-running version of the server is listening.
  2. Add a route GET /health that returns { "status": "ok" }.
  3. Add DELETE /todos?id=1 that removes an item and returns 204, or 404 if it does not exist.
  4. Save the list to a JSON file after each change, using the helpers from the previous lesson.
javascript
import http from "node:http";

const todos = [{ id: 1, text: "Learn Node", done: false }];

function sendJson(res, status, data) {
  res.writeHead(status, { "Content-Type": "application/json" });
  res.end(JSON.stringify(data));
}

function readBody(req) {
  return new Promise((resolve, reject) => {
    let body = "";
    req.on("data", chunk => (body += chunk));
    req.on("end", () => {
      try {
        resolve(body ? JSON.parse(body) : {});
      } catch {
        reject(new Error("Invalid JSON"));
      }
    });
    req.on("error", reject);
  });
}

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, "http://localhost");

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

    if (req.method === "POST" && url.pathname === "/todos") {
      const data = await readBody(req);
      if (!data.text) return sendJson(res, 400, { error: "text is required" });
      const todo = { id: Date.now(), text: data.text, done: false };
      todos.push(todo);
      return sendJson(res, 201, todo);
    }

    sendJson(res, 404, { error: "Not found" });
  } catch (error) {
    sendJson(res, 400, { error: error.message });
  }
});

server.listen(0, async () => {            // port 0 means "pick a free port"
  const base = `http://localhost:${server.address().port}`;

  let response = await fetch(`${base}/todos`);
  console.log(response.status, await response.json());

  response = await fetch(`${base}/todos`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text: "Build an API" }),
  });
  console.log(response.status, await response.json());

  response = await fetch(`${base}/todos`, { method: "POST", body: "{}" });
  console.log(response.status, await response.json());

  response = await fetch(`${base}/nothing`);
  console.log(response.status, await response.json());

  server.close();
});

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account