A tiny HTTP server with Node.js
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- 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
| Code | When |
|---|---|
| 200 | OK |
| 201 | Created something |
| 204 | OK with no body |
| 400 | The client sent something invalid |
| 404 | No such route or item |
| 500 | A 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.endtwice, or writing headers after the body started, throws an error. Usereturnafter 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.parsethrows, so catch it. - Hard-coding the port. Read
process.env.PORTso the server works in hosting environments.
Try it yourself
- Run the example and open the
/todosaddress in a browser while a longer-running version of the server is listening. - Add a route
GET /healththat returns{ "status": "ok" }. - Add
DELETE /todos?id=1that removes an item and returns 204, or 404 if it does not exist. - Save the list to a JSON file after each change, using the helpers from the previous lesson.
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