Explain it simply
A response in plain language
A response is the server's answer to one request, and it has three parts. The status code says in one number whether things went well or what went wrong. The headers are labels describing what is inside, such as Content-Type. The body is the actual data. Picture a waiter's nod, the label on a container, and the food inside it.
Good client code reads those parts in order: status first, then Content-Type, then the body. Code that jumps straight to res.json() works on the good days and breaks the moment an unusual response arrives.
Problem → Why → Solution
The problem: assuming every response is JSON
A developer writes code that reads one user: call res.json() and pull out the data field. It works on the happy path. But when the user does not exist, the body is { error: ... }, so data is undefined and a TypeError follows. If a DELETE is answered with 204, parsing the empty body as JSON throws a SyntaxError. And an HTML page from a gateway throws a SyntaxError as well.
// BROKEN: assumes every response is JSON with a "data" field
const res = await fetch("https://api.example.com/v1/users/u_9");
const { data } = await res.json();
console.log(data.name.toUpperCase());
// 404 -> body is { "error": ... }, so data is undefined: TypeError
// 204 -> res.json() throws on the empty body: SyntaxError
// 502 -> a gateway sends HTML: SyntaxError at the "<"One endpoint can answer in many shapes
An endpoint can answer with data on success, an error on failure, no body at all in some cases, and HTML when something in between breaks. Only the status code and Content-Type tell you which one arrived. So look at both before touching the body, and handle each shape on its own.
Core concept: status, then Content-Type, then body
The first line of a response is the status line (HTTP/1.1 200 OK), followed by one line per header, an empty line and then the body. The first digit of the status code gives the class: 2xx means success, 3xx means redirect or use your cache (304), 4xx means the client made a mistake, and 5xx means the server did. A client fixes its own request after a 4xx, and may simply try again later after a 5xx.
| Status | Meaning |
|---|---|
| 200 OK | Success, with a body |
| 201 Created | Something new exists; Location gives its URL |
| 204 No Content | Success, with no body at all |
| 400 / 422 | Malformed request / failed validation |
| 401 / 403 / 404 | Not authenticated / not allowed / not found |
| 429 | Too many requests; look at Retry-After |
| 500 / 502 / 503 | Server error / bad gateway / temporarily unavailable |
Content-Type says how to read the body (application/json; charset=utf-8). Call res.json() only when it says JSON; otherwise parsing a gateway's HTML error page throws a SyntaxError about an unexpected '<'. A 204 has no body at all, so res.json() fails with Unexpected end of JSON input, which is why you check for 204 first.
A body usually takes one of two shapes: a bare resource ({ "id": "u_1", ... }) or an envelope ({ "data": ..., "meta": ... }). An envelope leaves room for things like pagination in lists, while bare is simpler. Whichever you choose, keep one style across the whole API. Return errors in one shared shape such as { "error": { "code": ..., "message": ... } } on every endpoint, with the code for programs and the message for people. A flag such as "success": true repeats the status code, and the two can disagree.
- Status: success or failure?
- Content-Type: JSON or something else?
- Body empty? (204, HEAD)
- Parse: bare resource or envelope?
- Handle the error shape separately
Reading the body is the last step; before that, only the status and headers tell you how to read it.
General pattern
HTTP/1.1 <status code> <reason phrase>
Content-Type: application/json; charset=utf-8
<other headers>
success : { ...resource } or { "data": ..., "meta": ... }
error : { "error": { "code": "...", "message": "..." } }
204 : (no body, and no Content-Type)Every response has the same layout of status line, headers, empty line and body; what differs is the shape of the body.
Worked example: five response shapes, one parse()
The script below starts a server with five routes that answer in different shapes: a bare user, an envelope with a list, a 204, a JSON error and an HTML page from a gateway. A parse() helper checks status, Content-Type and body in order and turns every response into one { status, data, error } shape.
Look at the first output line first: it shows the error thrown when you call res.json() directly on a 204. After that you will see how parse() handles each of these responses without throwing.
import http from "node:http";
const alice = { id: "u_1", name: "Alice", nickname: null };
const server = http.createServer((req, res) => {
const send = (status, body) => {
if (body === undefined) {
res.writeHead(status); // 204: no headers about a body, and no body
return res.end();
}
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify(body));
};
const route = `${req.method} ${req.url}`;
if (route === "GET /users/u_1") return send(200, alice);
if (route === "GET /users") {
return send(200, { data: [{ id: "u_1", name: "Alice" }], meta: { total: 1 } });
}
if (route === "DELETE /users/u_1") return send(204);
if (route === "GET /users/u_9") {
const error = { code: "user_not_found", message: "No user with id u_9" };
return send(404, { error });
}
// What a proxy or gateway may return instead of your API's JSON.
res.writeHead(502, { "Content-Type": "text/html" });
res.end("<html><body>Bad Gateway</body></html>");
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
// One place that turns any response into { status, data, error }.
async function parse(res) {
if (res.status === 204) return { status: 204, data: null, error: null };
const type = res.headers.get("content-type") ?? "";
if (!type.includes("application/json")) {
const text = await res.text();
const error = { code: "not_json", message: text.slice(0, 22) };
return { status: res.status, data: null, error };
}
const json = await res.json();
if (!res.ok) return { status: res.status, data: null, error: json.error };
return { status: res.status, data: json.data ?? json, error: null };
}
const gone = await fetch(`${base}/users/u_1`, { method: "DELETE" });
try {
await gone.json();
} catch (err) {
console.log("json() on a 204:", err.name, "-", err.message);
}
const calls = [
["GET", "/users/u_1"],
["GET", "/users"],
["DELETE", "/users/u_1"],
["GET", "/users/u_9"],
["GET", "/oops"],
];
for (const [method, path] of calls) {
const result = await parse(await fetch(base + path, { method }));
console.log(method.padEnd(6), path.padEnd(11), JSON.stringify(result));
}
server.close();Code breakdown
- Bare and envelope
return send(200, { data: [{ id: "u_1", name: "Alice" }], meta: { total: 1 } });/users/u_1 returns a bare object while /users returns an envelope with data and meta. The demo mixes them only to show that parse() copes with both; in a real API, choose one style.
- 204 has no body
if (route === "DELETE /users/u_1") return send(204);When there is no body, send() only calls writeHead(status) and res.end(), with no Content-Type. That is the standard 204: it succeeded and has nothing to say.
- One error shape
const error = { code: "user_not_found", message: "No user with id u_9" };The error has the shape { error: { code, message } }. A program can switch on the code and a person can read the message. If every endpoint uses it, the client needs only one place to handle errors.
- A gateway's HTML
res.writeHead(502, { "Content-Type": "text/html" });Answering an unknown route with HTML imitates the 502 page that a proxy or load balancer sometimes returns. It is not your API's JSON, so the client must not assume JSON.
- Check Content-Type
if (!type.includes("application/json")) {Before calling res.json(), parse() checks Content-Type. If it is not JSON it reads res.text() and converts it to a not_json error, so no SyntaxError is thrown.
- Envelope or bare
return { status: res.status, data: json.data ?? json, error: null };If json.data exists it is an envelope; otherwise the whole body is the resource. Both successful shapes end up the same through this single line.
- json() on a 204
await gone.json();Calling json() directly on a 204 response in this line produces SyntaxError: Unexpected end of JSON input, which is why parse() checks for 204 first.
json() on a 204: SyntaxError - Unexpected end of JSON input
GET /users/u_1 {"status":200,"data":{"id":"u_1","name":"Alice","nickname":null},"error":null}
GET /users {"status":200,"data":[{"id":"u_1","name":"Alice"}],"error":null}
DELETE /users/u_1 {"status":204,"data":null,"error":null}
GET /users/u_9 {"status":404,"data":null,"error":{"code":"user_not_found","message":"No user with id u_9"}}
GET /oops {"status":502,"data":null,"error":{"code":"not_json","message":"<html><body>Bad Gatewa"}}Envelope or bare resource?
| Style | Looks like | Trade-off |
|---|---|---|
| Bare resource | { "id": "u_1", "name": "Alice" } | Simple, but a list has nowhere to put meta |
| Envelope | { "data": {...}, "meta": {...} } | Room for pagination and links, one extra layer to unwrap |
| Envelope with a success flag | { "success": true, "data": ..., "error": null } | Repeats the status code and can disagree with it |
The third style is common in tutorials, but a response that says success: true while arriving with HTTP status 500 leaves the client unsure which to believe. Keep the status code as the one place where truth lives. A small API with no need for meta can stay with bare resources, whereas an API with lists and pagination does better choosing an envelope from the start, because changing later forces every client to change.
Numbers, null and missing fields
A JSON number becomes a JavaScript double, so an integer above 2^53 - 1 (9007199254740991) cannot be stored exactly. Send large IDs as strings. null says 'known to be empty', while a missing field says 'not applicable here, or unknown'. JSON.stringify drops undefined but keeps null.
const raw = '{"id": 9007199254740993, "idText": "9007199254740993", "nickname": null}';
const user = JSON.parse(raw);
// A number above 2^53 - 1 silently loses precision; a string keeps every digit.
console.log(user.id, Number.isSafeInteger(user.id));
console.log(user.idText);
// null means "known to be empty"; a missing field is simply not there.
console.log("nickname" in user, user.nickname);
console.log("email" in user, user.email);
// JSON.stringify drops undefined but keeps null.
console.log(JSON.stringify({ a: undefined, b: null }));On the first line the id 9007199254740993 becomes 9007199254740992 and isSafeInteger is false, while the string version keeps every digit. The next two lines show nickname present as null and email absent. The last line shows a vanishing from stringify while b: null stays. So do not blur 'unknown' and 'empty' in your API, and document which you mean.
What json() says about a non-JSON body
The script below shows what happens when you call res.json() on a gateway's HTML page. Node 22's message even quotes the start of the offending text, so you can tell HTML arrived the moment you read it.
const gatewayPage = new Response("<html>Bad Gateway</html>", {
status: 502,
headers: { "Content-Type": "text/html" },
});
console.log(gatewayPage.headers.get("content-type"));
try {
await gatewayPage.json();
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}The first line shows the Content-Type and the second is the SyntaxError. If you check Content-Type first, you avoid this error and can raise a more useful one yourself, such as 'the gateway returned HTML'.
Error shape: problem details
Instead of inventing your own error format you can use RFC 9457, Problem Details for HTTP APIs. Its Content-Type is application/problem+json and it defines standard fields such as type, title, status and detail, to which you can add your own, like errors. It is not mandatory, but client libraries recognise it, so it is worth considering.
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/problems/validation",
"title": "Validation failed",
"status": 422,
"detail": "email must be a valid address",
"errors": [{ "field": "email", "message": "invalid format" }]
}Older documentation calls 422 Unprocessable Entity; the name changed but the code is the same. The api.example.com host in this example is purely illustrative.
In real projects
Reading responses in real projects
In real frontend and backend projects, the code that reads responses lives in one place, an API client helper. That way checking status, checking Content-Type, handling the error shape and sending the user back to login on a 401 are not rewritten for every endpoint. Monitoring also counts 4xx and 5xx separately by status class, so client mistakes and server failures are easy to tell apart.
- OpenAPI documentation and client generators can produce correct types only when responses share one shape.
- When a rate limit is hit, answer 429 with a Retry-After header and let the client wait that many seconds.
- ETag and Cache-Control headers tell clients and CDNs whether data may be cached, and 304 Not Modified answers with no body.
- A header such as X-Request-Id on every response lets a user's bug report lead you straight to the request in your server logs.
Common mistakes
Common mistakes with responses
Calling res.json() on a 204 or on HTML
A 204 has no body, which gives Unexpected end of JSON input, and a gateway's HTML gives a SyntaxError at an unexpected '<'. Check status and Content-Type first.
Returning an error with 200 OK
Returning { "success": false } with 200 makes clients that check res.ok, caches and monitoring treat it as success. Return errors with a real 4xx or 5xx.
Different error shapes on different endpoints
With { error: 'x' } in one place, { message: 'y' } in another and plain text elsewhere, the client grows more branches just to read errors. Decide on one error shape and let a single piece of middleware produce it.
Sending big IDs as numbers
An ID such as 9007199254740993 sent as a JSON number reads as 9007199254740992 in a JavaScript client, quietly pointing at the wrong record. Send IDs as strings.
Best practices
Best practices
- Read in the order status, Content-Type, body, and keep that order inside one helper.
- Use one success shape and one error shape across the whole API, and keep the status code as the single source of truth.
- Never put stack traces, SQL or internal host names in error responses; keep them in the server log.
- Send large IDs as strings, and document the difference between null and a missing field.
Mini challenge
Mini challenge: a products API with one error shape
Write a /products API in which every success is { data } (lists also carry meta.total) and every error is { error: { code, message } }. DELETE answers 204 with no body, an unknown route answers 404, and an unsupported method answers 405. When one route throws, record the details only in a server log and answer 500 with a generic message that reveals nothing.
- Produce one shape through two helpers, sendJson and fail
- Answer DELETE with 204, no Content-Type and no body
- Catch the throwing route, push err.message onto serverLog, and return internal_error to the client
- Call six URLs, print status and body (or (no body)), and print the server log too
import http from "node:http";
// TODO: a products array and a serverLog array
// TODO: sendJson(res, status, body) and fail(res, status, code, message)
// every success is { data: ... } (lists also get meta: { total })
// every error is { error: { code, message } }
// TODO: a server (port 0) handling
// GET /products, GET /products/<id>, DELETE /products/<id> (204, no body),
// unknown routes (404), unsupported methods (405)
// plus a route that throws: catch it, push err.message onto serverLog,
// and answer 500 with a generic message that does not reveal the details
// TODO: call six URLs with fetch, print "<method> <path> <status> <body or (no body)>",
// then print the server log and close the serverExpected: GET /products prints 200 with data and meta, /products/p_1 prints 200 with { data }, /products/p_9 prints 404 product_not_found, /products/boom prints 500 internal_error, DELETE prints 204 (no body), /nowhere prints 404 route_not_found, and the server log holds the ECONNREFUSED text.
Show hint
Wrap the whole request handler in try/catch, push err.message onto serverLog in the catch and call fail(res, 500, ...). For 204 use only res.writeHead(204) and res.end(), not sendJson. req.url.split('/') gives you the resource and the id.
Show solution
import http from "node:http";
const products = [{ id: "p_1", name: "Keyboard", price: 49 }];
const serverLog = [];
function sendJson(res, status, body) {
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify(body));
}
function fail(res, status, code, message) {
sendJson(res, status, { error: { code, message } });
}
const server = http.createServer((req, res) => {
try {
const [, resource, id] = req.url.split("/");
if (resource !== "products") {
return fail(res, 404, "route_not_found", "No such route");
}
if (req.method === "GET" && id === undefined) {
return sendJson(res, 200, { data: products, meta: { total: products.length } });
}
if (req.method === "GET" && id === "boom") {
throw new Error("connect ECONNREFUSED db.internal:5432");
}
if (req.method === "GET") {
const product = products.find((p) => p.id === id);
if (!product) return fail(res, 404, "product_not_found", `No product ${id}`);
return sendJson(res, 200, { data: product });
}
if (req.method === "DELETE") {
res.writeHead(204);
return res.end();
}
return fail(res, 405, "method_not_allowed", `${req.method} is not supported`);
} catch (err) {
serverLog.push(err.message); // the details stay on the server
return fail(res, 500, "internal_error", "Something went wrong");
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
for (const [method, path] of [
["GET", "/products"],
["GET", "/products/p_1"],
["GET", "/products/p_9"],
["GET", "/products/boom"],
["DELETE", "/products/p_1"],
["GET", "/nowhere"],
]) {
const res = await fetch(base + path, { method });
const text = await res.text();
console.log(`${method} ${path}`.padEnd(22), res.status, text || "(no body)");
}
console.log("server log:", serverLog.join(" | "));
server.close();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Read a response as status, then Content-Type, then body: 2xx is success, 4xx the client's fault, 5xx the server's.
- A 204 has no body so res.json() throws, and a gateway's HTML cannot be parsed either, which is why Content-Type is checked first.
- Keep one success shape (bare or envelope) and one { error: { code, message } } shape across the whole API.
- Send large IDs as strings, tell null from a missing field, and keep sensitive details out of error responses.
RFC 9110 — HTTP Semantics — IETF