Node.js Backend — What the Framework Hides
Stand Up an API With Node's Standard Library
Goal
Build a small order API with only the Node standard library, without Nest. You set up eight steps — a routing table, input validation, output shape, dependency injection, the event loop, and contract tests — and in the final ninth step you solve an incident in an order server that opens a real socket (some requests never get a response).
Why do it this way
The lab Pod has only DNS open, so npm install does not work. But that constraint actually
suits this course: if you make by hand the judgments that a framework makes for you,
then when you later read Nest you can see what each mechanism is doing on your behalf.
Format
Create /root/work/api/app.mjs and export the following.
handle(req)—reqis{method, path, body, headers}, and what you return is{status, body}. It does not open a real socket.createApp({store})— you build it in step 6.
The reason it does not open a socket is that grading must not be shaken by port conflicts or startup timing. A test is only useful if a failure means a real failure.
Steps
- The skeleton of
handle(req)and /healthz - Routing table — tell 404 from 405
- Input validation — 400 with a reason per field
- The shape you send out — an allowlist
- 404 for what does not exist
- The store by injection
- A slow path that does not block the event loop
- Contract tests without starting a server — the grader reruns them against versions that break the contract
- Incident nd-hang — three paths of an order server with a real socket never answer certain requests
Notes
- Steps 1–8 have no socket, so call it like
node -e 'import("/root/work/api/app.mjs").then(async m => console.log(await m.handle({method:"GET", path:"/items"})))'. - The step 9 incident is self-contained and independent of the earlier steps. First look at what a response that "never arrives" looks like with
curl -v -m 2. - Common mistakes: matching the method first and losing 405, removing fields with
delete, tests that always pass.
Set up the skeleton of the server
Direction: the skeleton of a server is "a function that takes one request and returns one response" — the socket is a job outside it. Tools: export async function in an ES module, mkdir -p /root/work/api, calling it with node -e. Specifics: /root/work/api/app.mjs exports handle(req); req is {method, path, body, headers}, and what you return is {status, body}. It is enough for /healthz alone to give 200 and {status:'ok'}.
handle('/healthz') returns 200 and {status:'ok'}
Build the routing table — tell 404 from 405
Direction: 404 and 405 are different events — "no such resource" and "the resource exists, but that action is not allowed". The order decides the verdict. Tools: an array holding {method, pattern, run} (the routing table), the regular expression exec. Specifics: if you match the method first, there is no place left to return 405. First collect the entries whose path matches, then look for the method among them. GET /items is an array.
A path that does not exist gives 404; another method on an existing path gives 405
Validate the input and say why it is wrong
Direction: the value of a 400 lies in telling "where to fix" — the mere fact that something is wrong gives the client nothing to do. Tools: typeof, Number.isFinite, an array that collects errors. Specifics: do not stop at the first error; collect {field, reason} for each field and return 400 with {errors: [...]}. The accepted shape is {name: string, qty: number}, and once created, return 201.
If qty is a string, 400 with qty in errors; if valid, 201
Separate the stored shape from the shape you send out
Direction: if you keep the stored shape and the outgoing shape separate, the API does not change silently when a column is added. Tools: a small function that picks fields with destructuring (for example ({id, name, qty}) => (...)), Array.prototype.map. Specifics: do not count what to remove, as in delete item.secret; count what to send out (an allowlist). Make the list, single-item, and just-created responses all pass through that one function.
The GET /items response has no secret and has id, name, and qty
Give 404 for what does not exist
Direction: the status code is the contract — clients read the status before the body. Tools: a regular expression capture in the routing table (/^\/items\/(\d+)$/), Number(...), the store's find. Specifics: if you give 200 and {error} for a nonexistent id, the client treats it as success. If it does not exist, 404; if it exists, 200 and that item (in the outgoing shape).
A nonexistent id gives 404; an existing id gives 200 and that item
Receive the store by injection
Direction: injection is marking in the code the place where something can be swapped in — testing simply gets easier as a result. Tools: a function that receives its dependency as an argument (createApp({store})), closures. Specifics: if even one line inside a handler still calls the global store directly, the fake store the grader passes in is ignored. Build the default handle as createApp({store: memoryStore}).
The store passed to createApp({store}) is actually used, and the output shape is preserved
Do not block the event loop
Direction: "slow" and "blocking" are different — other work must be able to run while you wait. Tools: a Promise wrapping setTimeout and await, and as the counterexample while (Date.now() < t). Specifics: GET /slow must take 40ms or more but release the event loop in the meantime. If you burn time in a busy loop, the grader's 5ms timer stops (the in-depth version of this topic is the node-event-loop course).
While four requests are handled concurrently, a 5ms timer keeps ticking
Test the contract without starting a server
Direction: the value of a test is "does it fail when things break" — a test that always passes protects nothing. Tools: test from node:test, node:assert/strict, a fake store passed to createApp. Specifics: the grader wraps your app.mjs and reruns your tests against three versions that each break one contract (secret leaks · 200 for a nonexistent id · qty validation off), and checks that assertions fail in two or more of them. Assert the output shape, 404, and 400 separately. Your tests must import ./app.mjs by a relative path for the grader's swapped-in versions to take effect. Do not open a port.
node --test passes, and assertions fail in two or more of the three contract-breaking versions (no server started)
Incident — some requests never get a response
Running incident nd-hang starts the incident. Three paths of the order API (orders-api, 127.0.0.1:8090) — order (GET /orders/), create (POST /orders), and receipt (GET /orders//receipt) — never answer certain requests (other requests on the same paths are fine, and the server has not died). Starting from the ticket and /srv/nd-hang/timeouts.txt, fix /srv/nd-hang/server.mjs, restart it with ndctl restart orders-api, and make all three paths answer to completion, and right away, with the status codes in /srv/nd-hang/API.md. The only places to fix are the functions of the three paths (getOrder, createOrder, getReceipt) and the request handler (the createServer callback), and covering up a wait with time (a timer) does not count as a fix. The grader also sends values different from those in the incident (nonexistent order numbers, unknown skus, and so on). In /root/incident/nd-hang/report.txt, write three lines order: <code>, create: <code>, and receipt: <code>, and for each path one line of the log (/var/log/nd/orders-api.log) that shows its cause, as evidence-order: <line>, evidence-create: <line>, and evidence-receipt: <line>. The cause is set separately for each path, so the same cause may appear twice. If you are wrong three times with different cause codes, the incident is withdrawn and you must start it again. The code is one of the following: missed-event (waiting for a notification that already went by), missing-end (a branch that never ends the response), slow-upstream (a slow downstream service), swallowed-rejection (a rejection nobody handled).
Direction: "no response arrives" also comes in three shapes — did the headers arrive but the end never came, did nothing arrive but an error was left in the log, or did nothing arrive and there is no error either. Tell them apart path by path. Tools: curl -v -m 2 (what arrived, and how many bytes), the aborted ... headersSent= and unhandledRejection: lines in the log, the lines printed at startup, and the one function for that path (getOrder, createOrder, getReceipt). Specifics: if it was cut off after the headers went out, look at the last call in that branch; if a rejection was logged, look at why that value was empty; if there is no trace at all, look at what that function waits for with await and when that happened (the time in the startup log). If you do not restart, the fixed code is not loaded.