Sub topic 10
What a server does with a request
This chapter assumes you can read an HTTP request and response, know the common methods and status codes, and can run a Node.js script (version 18 or later) from a terminal. It covers what happens on the server side between the moment bytes arrive and the moment a response goes out.
The server's job in five steps
A web server program listens on a port. Each time a client sends a request, the server does roughly the same work:
- Parse the raw bytes into a method, a path, headers, and an optional body.
- Route the request, which means choosing the code that should handle that method and path.
- Validate the input and check that the client is allowed to do this.
- Do the work, such as reading a file or querying a database.
- Build a response with a status code, headers, and a body.
Most real servers use a framework that does steps 1 and 2 for you. The logic underneath is the same, so it is worth seeing once without a framework.
A small server with routing
The server below keeps notes in memory. It has one path, /notes, and supports two methods on it.
import { createServer } from "node:http";
const notes = [];
function sendJson(res, status, data, extraHeaders = {}) {
const body = JSON.stringify(data);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(body),
...extraHeaders,
});
res.end(body);
}
async function readBody(req) {
req.setEncoding("utf8");
let text = "";
for await (const chunk of req) text += chunk;
return text;
}
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${req.headers.host ?? "localhost"}`);
if (url.pathname !== "/notes") {
return sendJson(res, 404, { error: "Not found" });
}
if (req.method === "GET") {
return sendJson(res, 200, notes);
}
if (req.method === "POST") {
const type = req.headers["content-type"] ?? "";
if (!type.startsWith("application/json")) {
return sendJson(res, 415, { error: "Send application/json" });
}
let data;
try {
data = JSON.parse(await readBody(req));
} catch {
return sendJson(res, 400, { error: "Body is not valid JSON" });
}
if (typeof data?.text !== "string" || data.text.trim() === "") {
return sendJson(res, 422, { error: "Field 'text' is required" });
}
const note = { id: notes.length + 1, text: data.text };
notes.push(note);
return sendJson(res, 201, note, { Location: `/notes/${note.id}` });
}
return sendJson(res, 405, { error: "Method not allowed" }, { Allow: "GET, POST" });
} catch (err) {
console.error(err);
return sendJson(res, 500, { error: "Internal server error" });
}
});
server.listen(3000, () => console.log("Listening on http://localhost:3000"));Save it as server.mjs, run node server.mjs, and try it from a second terminal:
curl -i -X POST http://localhost:3000/notes \
-H "Content-Type: application/json" \
-d '{"text":"buy milk"}'
curl -i http://localhost:3000/notes
curl -i -X DELETE http://localhost:3000/notes
curl -i http://localhost:3000/missingThe first call returns 201 Created with a Location header. The GET returns 200 and the stored list. The DELETE returns 405 with an Allow header. The last call returns 404.
Routing: path first, then method
Routing is a lookup. The server compares the path (and sometimes the host) against its known routes, then compares the method against what that route supports. Keeping the two checks separate lets the server give two different answers:
- No route matches the path:
404 Not Found. - The path exists but not for this method:
405 Method Not Allowed, with anAllowheader listing the methods that do work.
Parse req.url with a URL parser instead of comparing raw strings. The raw value includes the query string, so /notes?limit=5 would not equal /notes. The parser separates pathname from search for you.
Reading the body and the headers that describe it
A request body arrives as a stream of chunks, not all at once. A handler has to read it to the end before parsing. The Content-Type request header tells the server how to interpret those bytes. If a client sends form data to a handler that expects JSON, JSON.parse fails, and the server should respond with an error instead of crashing.
Servers should also limit body size. Without a limit, a client can send gigabytes and exhaust memory. Production servers and frameworks enforce a maximum and reply 413 Content Too Large when it is exceeded. The example above omits this limit to stay short, so do not expose it to the internet as written.
Choosing the status code
The code should describe what actually happened. These are the ones the example uses:
| Situation | Status | Why |
|---|---|---|
| Body is not parseable JSON | 400 | The request is malformed. |
| Wrong `Content-Type` | 415 | The server does not accept that format. |
| JSON parses but a field is missing | 422 | The syntax is fine, the content is not acceptable. |
| Resource created | 201 | Success, plus a `Location` header pointing to the new item. |
| Unknown path | 404 | Nothing lives there. |
| Known path, unsupported method | 405 | Add an `Allow` header. |
| Unexpected exception | 500 | The fault is on the server, not the client. |
Some teams use 400 for all validation problems. Pick one convention and apply it everywhere, because clients will write code against it.
Validation, authentication, and authorization
Treat everything in a request as untrusted, including headers, the path, query values, and cookies. Validate at the point where data enters your program.
Two checks are easy to confuse:
- Authentication asks who you are. A missing or invalid credential gets
401 Unauthorized. - Authorization asks whether you may do this. A known user who lacks permission gets
403 Forbidden.
Credentials usually arrive in the Authorization header or in a cookie, which the handler reads from the request headers.
Common errors
- Sending a response twice. After
res.end()the response is finished. A secondwriteHeadorendcall, often caused by a missingreturn, throws an error. The example usesreturn sendJson(...)for this reason. - Forgetting the catch-all. An uncaught exception in a handler can crash the process or leave the client waiting. Wrap handlers so any failure becomes a
500. - Leaking internals. Log the stack trace on the server and send the client a short, generic message. Stack traces and database errors reveal how your system works.
- Wrong
Content-Length. If it is smaller than the real body, the client truncates the response. If it is larger, the client waits for bytes that never come.Buffer.byteLengthcounts bytes, whilestring.lengthcounts characters, and the two differ for non-ASCII text. - Treating
GETas safe to change state. Browsers, caches, and crawlers repeatGETrequests freely, so aGEThandler that deletes data will eventually be triggered by accident.
Statelessness
Each request is handled on its own. The server does not remember the previous request unless you store something. The notes array lives in process memory, so a restart erases it, and two server processes would each hold a different list. Real applications put such state in a database and identify returning users with a cookie, which a later chapter covers.
Exercise
Your server receives PUT /notes and the route exists only for GET and POST. Which status code and which header should the response include, and why is 404 the wrong choice?
Show answer
Respond with 405 Method Not Allowed and an Allow: GET, POST header. A 404 says the resource does not exist, but /notes does exist and only the method is unsupported. The Allow header tells the client which methods it can use instead.
Exercise
A client sends POST /notes with the body {"text": ""} and Content-Type: application/json. Using the server above, which status does it return, and which step of the five-step flow rejects it?
Show answer
It returns 422. The body parses as valid JSON, so the parsing step passes. The validation step then finds that text is an empty string and rejects it before the handler stores anything.