In the last lesson, you watched Node.js call your listener once per request, with the method, URL, and headers in req. Yet your server still answers every request with the same line of plain text. Mrs. Okafor’s callers want facts about plots, and the finished board sent those as JSON with a status code that matched the answer.
In this lesson, you’ll make those decisions yourself. You’ll choose the status code and the Content-Type header, send the plot list as JSON, and send failures in one consistent shape. Start with the response you already send, and make it say what it is.
Choose the Status and the Content Type
So far, curl -i has shown your server answering 200 OK with no Content-Type header, and your code chose neither. Node.js uses 200 when you set no status, and it can’t know what your body is, so a client has to guess.
The res object lets you decide both. Change the listener in server.ts to set them with two statements before res.end():
server.ts
import { createServer } from "node:http";
const PORT = 3000;
const server = createServer((req, res) => {
console.log(req.method, req.url);
res.statusCode = 200;
res.setHeader(
"Content-Type",
"text/plain; charset=utf-8",
);
res.end("Hello from the Hollybank plot board!\n");
});
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
The res.statusCode property holds the status code that goes on the response’s first line. The res.setHeader() method adds a response header, and this call sets Content-Type to text/plain; charset=utf-8. That value tells the client the body is plain text, encoded as UTF-8.
If your server isn’t still running with node --watch server.ts from the last lesson, start it that way now. Save the file, and then ask for the home page from your second terminal:
$ curl -i http://localhost:3000/
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Thu, 26 Nov 2026 15:01:51 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 37
Hello from the Hollybank plot board!
The Content-Type line appears because you set the header, and the 200 now comes from your code. Before, Node.js filled it in for you. Both must be set before res.end(), because res.end() sends the status line and headers along with the body.
Send the Plot List as JSON
Mrs. Okafor’s callers ask about plots, so the board should answer with the data from plots.json. The code that reads the file goes in a module of its own. Create plots.ts next to server.ts:
plots.ts
import { readFile } from "node:fs/promises";
export type Plot = {
number: number;
size: number;
holder: string | null;
};
const text = await readFile("plots.json", "utf8");
const plots: Plot[] = JSON.parse(text);
export function getPlots(): Plot[] {
return plots;
}
The await readFile() line runs once, when the server starts and first imports this module. After that, getPlots() hands back the same array for every request.
The Plot type describes each plot, with holder as null for a vacant one. The file is the society’s own data, so the code trusts its shape. Data that arrives in a request never gets that trust.
Node.js reads plots.json from the folder you start the server in, not from beside plots.ts, so always run it from the project folder. Otherwise, the server stops at startup with an error saying it can’t find plots.json.
Notice that plots.ts says nothing about requests, responses, or status codes. A module like this is a data module. It knows the plots and nothing about HTTP, so any part of the server can use it, and you can test it without starting a server. The listener’s job is to ask it for data and decide how to answer.
The JSON body needs a different Content-Type, application/json; charset=utf-8. If you’ve only ever been the client, your first attempt might be to hand the plot array straight to res.end(). Import getPlots() at the top of server.ts. Node.js needs the .ts extension in the import path to find the file. Then change the listener:
server.ts
import { createServer } from "node:http";
import { getPlots } from "./plots.ts";
const PORT = 3000;
const server = createServer((req, res) => {
console.log(req.method, req.url);
res.statusCode = 200;
res.setHeader(
"Content-Type",
"application/json; charset=utf-8",
);
res.end(getPlots());
});
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
Run npm run check, and it reports no type errors. Save the file, and before you run the next command, predict what curl will show:
$ curl -i http://localhost:3000/plots
$ curl -i http://localhost:3000/plots
curl: (52) Empty reply from server
There’s no status line at all. The server’s terminal explains why:
GET /plots
node:_http_outgoing:1071
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be ...
...
Failed running 'server.ts'. Waiting for file changes before restarting...
The error’s message is longer than the line shown above. In full, it says the chunk “must be of type string or an instance of Buffer or Uint8Array. Received an instance of Array.” The chunk is the array you passed to res.end().
A response body travels as bytes, so res.end() accepts a string or bytes, never an array or an object. The TypeError crashed the whole program, so the server stopped and curl got an empty reply. The type check didn’t help, because Node.js’s type definitions accept any value as the first argument to res.end().
Turning data into text is a job you’ve done before, from the other side. A client calls JSON.stringify() before it sends a request body, and the server must do the same before it sends a response body.
If the crash still puzzles you, the button below opens a conversation with the AI mentor, where you can talk it through before you fix it:
Rather than repeat the status, the header, and the JSON.stringify() call wherever you answer with JSON, put them in one function. Create responses.ts next to server.ts:
responses.ts
import type { ServerResponse } from "node:http";
export function sendJson(
res: ServerResponse,
status: number,
data: unknown,
): void {
res.statusCode = status;
res.setHeader(
"Content-Type",
"application/json; charset=utf-8",
);
res.end(JSON.stringify(data));
}
The sendJson() function takes the response, a status, and the data, and it’s the one place a JSON response goes out. The unknown type lets any value past the type check, but the data must still be something JSON.stringify() can turn into JSON text, such as the plot array. Pass undefined, and the client gets an empty body labeled as JSON.
The import type line brings in only the ServerResponse type, as the project’s verbatimModuleSyntax setting requires for a name used only as a type.
In server.ts, import sendJson() from ./responses.ts, and replace the listener’s res.statusCode assignment and its calls to res.setHeader() and res.end() with one call:
sendJson(res, 200, getPlots());
Save the file, which restarts the crashed server, and ask for the plot list again:
$ curl -i http://localhost:3000/plots
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Thu, 26 Nov 2026 15:02:47 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 1134
[{"number":1,"size":250,"holder":"Gloria Mendes"},...]
The body contains all twenty-four plots on one line, shortened here. Your server now decides the status, the Content-Type, and the JSON body, as the finished board did.
Send Every Failure in One Shape
Your listener answers every request the same way, so /plots/7 also gets the whole list with 200 OK, and a client would take that as plot 7’s answer. A path your server doesn’t handle yet should get a 404.
A failure also needs a body that tells the client what went wrong. The finished board answered plot 99 with an error object, and every failure in your server will use its shape from now on: { error: { code, message, details } }. The code is a short, fixed name a program can check, the message is a sentence for a person, and details holds anything extra, or null when there’s nothing.
Why null instead of leaving details out? A short session in Node.js’s interactive shell, or REPL, shows what JSON.stringify() does with undefined:
> JSON.stringify({ code: "not_found", details: undefined })
'{"code":"not_found"}'
> JSON.stringify({ code: "not_found", details: null })
'{"code":"not_found","details":null}'
A property set to undefined disappears from the JSON, while null stays. If you default details to null, then every error body has all three keys, so a client can rely on the shape.
Add sendError() to responses.ts, below sendJson():
responses.ts
export function sendError(
res: ServerResponse,
status: number,
code: string,
message: string,
details: unknown = null,
): void {
const error = { code, message, details };
sendJson(res, status, { error });
}
The sendError() function builds the error object and sends it through sendJson(), so a failure gets the same Content-Type as every other JSON response. Thanks to its default value, you can leave details out when there’s nothing extra to say.
Now give the listener a choice. Import sendError() beside sendJson(), and send the list only when req.url is exactly /plots:
server.ts
import { createServer } from "node:http";
import { getPlots } from "./plots.ts";
import { sendError, sendJson } from "./responses.ts";
const PORT = 3000;
const server = createServer((req, res) => {
console.log(req.method, req.url);
if (req.url === "/plots") {
sendJson(res, 200, getPlots());
} else {
const message = `Nothing at ${req.url}.`;
sendError(res, 404, "not_found", message);
}
});
server.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
The === operator compares the whole request target in req.url, not only its path. Query strings and the request’s method come in later lessons.
The listener stays thin. It asks plots.ts for data and hands the answer to a helper. Save, and ask for plot 7, which your server doesn’t handle yet:
$ curl -i http://localhost:3000/plots/7
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 26 Nov 2026 15:02:47 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 78
{"error":{"code":"not_found","message":"Nothing at /plots/7.","details":null}}
Your server chose 404 Not Found, labeled the body as JSON, and sent the error in the consistent shape, with details set to null.
Use the AI mentor to work through how a program calling your server would use that shape:
Before you move on, make one change on your own. The home page, /, now gets a 404. Make it send the plain-text greeting again with 200, while /plots and the 404 keep working. Then call all three with curl -i, and say which res.end() runs for each.
Add a branch for / in front of the others:
if (req.url === "/") {
res.statusCode = 200;
res.setHeader(
"Content-Type",
"text/plain; charset=utf-8",
);
res.end("Hello from the Hollybank plot board!\n");
} else if (req.url === "/plots") {
sendJson(res, 200, getPlots());
} else {
const message = `Nothing at ${req.url}.`;
sendError(res, 404, "not_found", message);
}
The greeting is back:
$ curl -i http://localhost:3000/
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Thu, 26 Nov 2026 15:09:27 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Content-Length: 37
Hello from the Hollybank plot board!
Each path runs exactly one res.end(). For /, it’s the one in the first branch. For /plots, it’s the one in sendJson(), and any other path reaches that same call through sendError().
Then check that you can explain what you built:
- What happens when a listener passes the plot array straight to
res.end(), and what’s the fix? - Why does
sendError()defaultdetailstonull? - Why does
plots.tscontain nothing about requests or responses?
- Node.js throws a
TypeErrorbecause a body must be a string or bytes. The server crashes, and the client gets an empty reply. The fix is to send the string returned byJSON.stringify(), whichsendJson()does for you. JSON.stringify()leaves out a property set toundefined, but keeps one set tonull. Withnull, every error body hascode,message, anddetails.- It’s a data module, so it only knows the plots. The listener decides the status and headers, and you can reuse and test the data code without a server.
Your server now chooses its own status codes and sends errors in a consistent JSON shape, and every request it gets ends with a response. In the next lesson, Answer Every Request Exactly Once, you’ll see what happens to a client when a path through the listener never sends one.