HTTP Module
Build a raw HTTP server, handle routes, and understand req/res.
A server in five lines
The built-in http module lets Node speak the web's protocol with no dependencies. http.createServer(handler) builds a server; the handler runs once per incoming request, receiving two objects:
req(IncomingMessage) — everything about the request: method, URL, headers, bodyres(ServerResponse) — your tools for replying: status code, headers, body
server.listen(port) binds to a port and starts accepting connections. One Node process handles many simultaneous requests — each just schedules callbacks on the event loop.
const http = require("http");
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello, web!\n");
});
server.listen(3000, () => {
console.log("Listening on http://localhost:3000");
});The request: method, URL, headers
Everything the client sent is on req:
req.method—"GET","POST","PUT","DELETE"...req.url— the path and query string, like"/users?page=2"(not the full URL)req.headers— an object of lowercased header names
To split the path from query parameters, parse req.url with the WHATWG URL class. Query values are always strings.
const http = require("http");
const server = http.createServer((req, res) => {
// req.url is like "/search?q=node&page=2"
const url = new URL(req.url, "http://" + req.headers.host);
console.log("method:", req.method);
console.log("path: ", url.pathname);
console.log("query q:", url.searchParams.get("q"));
res.end("Check the server console!");
});
server.listen(3000);The response: status, headers, body
You compose a response in three steps — in this order:
- Status code:
res.statusCode = 404, orres.writeHead(404, {...})to set headers at the same time - Headers:
res.setHeader("Content-Type", "application/json")— must happen *before* any body is written - Body:
res.write(chunk)zero or more times, thenres.end()— or pass the final chunk straight toend()
Every request must be ended. Forgetting res.end() leaves the client hanging until it times out. For JSON APIs, set the content type and JSON.stringify the payload.
const http = require("http");
const server = http.createServer((req, res) => {
const payload = { message: "ok", time: new Date().toISOString() };
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(payload));
});
server.listen(3000);
// curl localhost:3000 -> {"message":"ok","time":"..."}Routing by hand
The raw http module has no router — one handler receives every request, and you branch on req.method and the path yourself. A small route table keeps this tidy... for a while. Feeling how quickly manual routing gets painful is the best preparation for the next lesson, where Express solves it.
Unmatched paths should get a 404 status, and unsupported methods a 405.
const http = require("http");
const server = http.createServer((req, res) => {
const { method, url } = req;
if (method === "GET" && url === "/") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("home");
} else if (method === "GET" && url === "/api/users") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify([{ id: 1, name: "Ada" }]));
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Not found: " + url }));
}
});
server.listen(3000);Reading a request body
POST and PUT requests carry a body — and here the http module shows its streaming nature: the body arrives in chunks via data events on req, followed by end. You collect the chunks, concatenate, and parse.
Always wrap JSON.parse in try/catch — clients send malformed JSON constantly, and an uncaught parse error would crash the server. Respond with 400 Bad Request instead.
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method !== "POST") {
res.writeHead(405).end();
return;
}
let raw = "";
req.on("data", (chunk) => { raw += chunk; });
req.on("end", () => {
try {
const body = JSON.parse(raw);
res.writeHead(201, { "Content-Type": "application/json" });
res.end(JSON.stringify({ received: body }));
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Invalid JSON" }));
}
});
});
server.listen(3000);Status codes you must know
HTTP status codes are grouped by their first digit:
- 2xx success — 200 OK, 201 Created (after a successful POST), 204 No Content (successful DELETE)
- 3xx redirection — 301 Moved Permanently, 304 Not Modified (caching)
- 4xx client errors — 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
- 5xx server errors — 500 Internal Server Error, 503 Service Unavailable
The golden rule: 4xx means *the client* did something wrong; 5xx means *your server* did. Getting these right makes your API predictable for every client and tool.
Check your understanding
5 questionsQuestion 1 of 5
Score: 0