HTTP in Node: Servers, Routing, Static Files and Clients
Build HTTP servers with node:http: request and response objects, routing with URL, reading JSON bodies safely, status codes and headers, a streaming static file server with a path traversal guard, HTTP clients with fetch and http.request, HTTPS, and why frameworks exist.
kvi5hnuCode Sprout team member7 min readOn this page
Node's node:http, node:https and node:http2 modules implement the HTTP protocol directly. They're fairly low level: no routing, body parsing or cookies. Frameworks such as Express, Fastify, Hono and Koa build on them. Writing a small server by hand is still worth doing once, because every framework hides the same two objects underneath.
Request and response
http.createServer(handler) creates a server, and server.listen(port) starts accepting connections. For every request, the handler receives two streams:

req(http.IncomingMessage) is a readable stream of the request body, withreq.method("GET","POST", ...),req.url(only the path and query string, for example"/items?page=2"), andreq.headers(names in lowercase).res(http.ServerResponse) is a writable stream for the response. Set the status and headers withres.statusCodeandres.setHeader(name, value), or both at once withres.writeHead(status, headers). Then send the body withres.write(chunk)and finish withres.end(lastChunk?). Every request must end withres.end(), or the client waits until it times out.
Headers are sent before the first byte of the body, so once you've called write, you can't change them; res.headersSent tells you whether that has happened.
A JSON API
The example below implements two routes, reads a JSON body with a size limit, and returns proper status codes. It runs the server on port 0, which asks the operating system for any free port, and talks to it with fetch:
const http = require("node:http");
const { once } = require("node:events");
const todos = [{ id: 1, title: "learn streams", done: true }];
async function readJSONBody(req, limit = 1_000_000) {
const chunks = [];
let size = 0;
for await (const chunk of req) { // the request is a readable stream
size += chunk.length;
if (size > limit) throw Object.assign(new Error("body too large"), { status: 413 });
chunks.push(chunk);
}
try {
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch {
throw Object.assign(new Error("invalid JSON"), { status: 400 });
}
}
function sendJSON(res, status, data) {
const body = JSON.stringify(data);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
});
res.end(body);
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost"); // req.url is only the path + query
try {
if (req.method === "GET" && url.pathname === "/todos") {
const done = url.searchParams.get("done");
const list = done === null ? todos : todos.filter((t) => String(t.done) === done);
return sendJSON(res, 200, list);
}
if (req.method === "POST" && url.pathname === "/todos") {
const { title } = await readJSONBody(req);
if (typeof title !== "string" || !title) return sendJSON(res, 422, { error: "title required" });
const todo = { id: todos.length + 1, title, done: false };
todos.push(todo);
res.setHeader("Location", `/todos/${todo.id}`);
return sendJSON(res, 201, todo);
}
sendJSON(res, 404, { error: `no route for ${req.method} ${url.pathname}` });
} catch (err) {
sendJSON(res, err.status ?? 500, { error: err.status ? err.message : "internal error" });
}
});
async function main() {
server.listen(0); // 0: any free port
await once(server, "listening");
const base = `http://localhost:${server.address().port}`;
let res = await fetch(`${base}/todos`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "write a server" }),
});
console.log(res.status, res.headers.get("location"), await res.json());
res = await fetch(`${base}/todos?done=false`);
console.log(res.status, await res.json());
res = await fetch(`${base}/todos`, { method: "POST", body: "{not json" });
console.log(res.status, await res.json());
res = await fetch(`${base}/users`);
console.log(res.status, await res.json());
server.close();
}
main();
201 /todos/2 { id: 2, title: 'write a server', done: false }
200 [ { id: 2, title: 'write a server', done: false } ]
400 { error: 'invalid JSON' }
404 { error: 'no route for GET /users' }
The important details:
- Routing: parse
req.urlwithnew URL(req.url, base)(article 88) to getpathnameandsearchParams, then branch on method and path. The legacyurl.parse()function, which a lot of older code uses, is deprecated. - Reading the body: iterate the request stream, limiting its size. Without a limit, a client can send gigabytes and exhaust the server's memory. Invalid JSON is the client's fault (
400), not a server crash. - Status codes:
200OK,201Created (with aLocationheader),204No Content,400Bad Request,401/403unauthenticated/forbidden,404Not Found,405Method Not Allowed,413Payload Too Large,422invalid data,500server error. - Errors: the
try/catchmakes sure every request gets an answer. Don't send internal error messages or stack traces to clients; log them instead. Content-Typetells the client how to interpret the body, andContent-Lengthmust be the byte length (Buffer.byteLength), not the string length (article 124).
Serving static files
A static file server maps URL paths to files and streams them, with pipeline, so large files use little memory and slow clients get backpressure (article 127):
const http = require("node:http");
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const os = require("node:os");
const path = require("node:path");
const { pipeline } = require("node:stream/promises");
const { once } = require("node:events");
const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".png": "image/png" };
function staticServer(root) {
return http.createServer(async (req, res) => {
if (req.method !== "GET" && req.method !== "HEAD") {
res.writeHead(405, { Allow: "GET, HEAD" }).end();
return;
}
const { pathname } = new URL(req.url, "http://x");
let file = path.resolve(root, "." + decodeURIComponent(pathname));
if (file !== root && !file.startsWith(root + path.sep)) { // path traversal guard
res.writeHead(403).end("forbidden");
return;
}
try {
let st = await fsp.stat(file);
if (st.isDirectory()) {
file = path.join(file, "index.html");
st = await fsp.stat(file);
}
res.writeHead(200, {
"Content-Type": TYPES[path.extname(file)] ?? "application/octet-stream",
"Content-Length": st.size,
});
if (req.method === "HEAD") return res.end();
await pipeline(fs.createReadStream(file), res); // streamed, with backpressure
} catch (err) {
if (!res.headersSent) res.writeHead(err.code === "ENOENT" ? 404 : 500).end();
}
});
}
// A client built on http.request, for comparison with fetch
function get(url) {
return new Promise((resolve, reject) => {
const req = http.request(url, { method: "GET" }, async (res) => {
let body = "";
res.setEncoding("utf8");
for await (const chunk of res) body += chunk;
resolve({ status: res.statusCode, type: res.headers["content-type"], body });
});
req.on("error", reject);
req.end(); // send the request (no body)
});
}
async function main() {
const root = await fsp.mkdtemp(path.join(os.tmpdir(), "site-"));
await fsp.writeFile(path.join(root, "index.html"), "<h1>Home</h1>");
await fsp.writeFile(path.join(root, "app.css"), "h1 { color: teal }");
const server = staticServer(root).listen(0);
await once(server, "listening");
const base = `http://localhost:${server.address().port}`;
console.log(await get(`${base}/`));
console.log(await get(`${base}/app.css`));
console.log((await get(`${base}/missing.txt`)).status);
console.log((await get(`${base}/..%2f..%2fetc%2fpasswd`)).status); // encoded "../"
server.close();
await fsp.rm(root, { recursive: true });
}
main();
{
status: 200,
type: 'text/html; charset=utf-8',
body: '<h1>Home</h1>'
}
{ status: 200, type: 'text/css', body: 'h1 { color: teal }' }
404
403
Note the traversal guard. Decoding the path turns ..%2f into ../, which path.resolve follows out of the root, so the server checks where the final path ended up (article 128). A common mistake is stripping ../ with a regular expression, which is easy to bypass: removing ../ from ....// leaves ../. Always validate the resolved path instead of trying to clean the input.
Production static servers also handle caching headers (ETag, Last-Modified, Cache-Control), compression and byte ranges (Range requests, for video). Use a library for that, such as serve-static or your framework's static middleware, or a reverse proxy like nginx in front of Node.
HTTP clients
fetch(article 117) is built into Node and is the right default: promises, web-standardRequest/Response/Headers, streaming bodies, andAbortSignal.timeout(ms)for timeouts.http.request(url, options, callback)is the low-level client. You write the body withreq.write(), must callreq.end()to send the request, and receive anIncomingMessageresponse stream.http.getis a shortcut that callsend()for you. It's mostly used by libraries and for unusual needs; note the"error"listener, without which a failed connection crashes the process.
HTTPS and HTTP/2
https.createServer({ key, cert }, handler) serves HTTPS given a TLS private key and certificate, read from files. In production, TLS is usually handled by a load balancer or reverse proxy in front of Node, and Node serves plain HTTP behind it. node:http2 supports HTTP/2, which multiplexes many requests over one connection.
Production concerns
A real server also needs:
- Graceful shutdown:
server.close()stops accepting new connections and waits for active requests (article 122).server.closeIdleConnections()closes idle keep-alive connections. - Timeouts:
server.requestTimeout(5 minutes by default) andserver.headersTimeoutprotect against clients that send very slowly. - Security: limit body sizes, validate input, set security headers, and never build file paths, SQL or shell commands from unchecked input.
- Concurrency: one Node process uses one CPU core for JavaScript. To use all cores, run several processes behind a load balancer, or use the
node:clustermodule, which forks workers that share a port.
Frameworks package routing, body parsing, middleware, validation and error handling, which is why most production servers use one.
Common questions
Why does my request hang forever?
On the server, some path through the handler never calls res.end(), often an error branch. On a client using http.request, you forgot req.end(), so the request was never sent.
Why do I get "Cannot set headers after they are sent"?
The code called setHeader or writeHead after the response had started, typically by responding twice: for example, a missing return after sending an error, so execution continued to the normal response.
Should I use http directly or a framework?
Use the http module to learn, and for tiny services or tools such as a test server. For applications, a framework gives you routing, middleware, body parsing and error handling that are already tested.
Summary
http.createServer((req, res) => ...):reqis a readable stream withmethod,urlandheaders;resis a writable stream withwriteHead/setHeader,writeandend.- Route with
new URL(req.url, base); read bodies withfor awaitand a size limit; reply with correct status codes,Content-Typeand byte-accurateContent-Length. - Serve files by streaming them with
pipeline, and validate resolved paths against the root to prevent traversal. - Use
fetchas the client;http.requestis the low-level alternative and needsreq.end()and an error listener. - Production servers need timeouts, graceful shutdown and input limits, and usually a framework.
Practice Questions
A handler does res.end("ok") in a callback, but only inside an if. What happens to requests that don't take that branch?
Answer
They never receive a response. The client waits until a timeout, and the connection stays open on the server. Every path through a handler must end the response.
Why is req.url not enough to read a query parameter, and how do you get page from /items?page=3?
Answer
req.url is just the string "/items?page=3". Parse it: new URL(req.url, "http://localhost").searchParams.get("page") returns "3", a string that you may need to convert with Number.
Write a handler that responds to GET /health with status 200 and the JSON {"ok":true}, and to everything else with 404.
Answer
const http = require("node:http");
http.createServer((req, res) => {
if (req.method === "GET" && new URL(req.url, "http://x").pathname === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true }));
} else {
res.writeHead(404).end();
}
}).listen(3000);
What's the risk of reading a request body without a size limit?
Answer
A client can send an enormous body, and the server buffers all of it in memory. A few such requests can exhaust memory and crash the server, which is a denial-of-service attack. Stop reading and respond with 413 once the limit is exceeded.
Previous: Writing Files, File Operations, Metadata and Directories in Node

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.