In a Node.js http.createServer handler, what are the req and res objects, and how do you read a JSON request body without a framework?
answer
- one stream per direction
- IncomingMessage is a Readable
- the body arrives in chunks
- ServerResponse is a Writable you must end
- no parsing and no size limit built in
basics
~10 sreq is an http.IncomingMessage: parsed headers plus a Readable stream of body bytes. res is an http.ServerResponse, a Writable. You collect the body chunks yourself, parse them, and must call res.end().
solid answer
~40 s`http.createServer` calls the handler with `req`, an `http.IncomingMessage`, and `res`, an `http.ServerResponse`. By the time the handler runs, Node has parsed the request line and headers (`req.method`, `req.url`, lower-cased `req.headers`), but the body has not arrived: `req` is a `Readable`, so you gather its `Buffer` chunks with `for await` or `'data'`/`'end'`, `Buffer.concat` them, decode and `JSON.parse` inside a `try`. `res` is a `Writable`: set the status and headers, write the body, and always call `res.end()`, or the client waits until a timeout. Node gives you no router, no body parser and no body-size limit; that is the layer Express and its body-parsing middleware add.
code
javascript · 31 linesimport { createServer } from 'node:http';
const LIMIT = 1_000_000; // bytes
createServer((req, res) => {
const chunks = [];
let size = 0;
req.on('error', () => res.destroy());
req.on('data', (chunk) => {
size += chunk.length;
if (size > LIMIT) {
if (!res.headersSent) {
res.writeHead(413, { 'Content-Type': 'text/plain', Connection: 'close' });
res.end('body too large');
}
return;
}
chunks.push(chunk);
});
req.on('end', () => {
if (res.headersSent) return;
try {
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: Object.keys(body) }));
} catch {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('invalid JSON');
}
});
}).listen(3000);go deeper
Name the two classes, IncomingMessage and ServerResponse, say which is readable and which is writable, and show the collect-concat-parse sequence ending in res.end().
Explain why the body is not ready when the handler runs, why Buffer.concat beats per-chunk decoding, and what Node does with a body the handler never reads.
Treat the raw server as hostile input: cap the body as it streams, catch async handler errors before they become uncaught exceptions, and answer with a status code yourself.
Be able to say which protections a framework layer supplies by default, and which the team must own when a service is written directly on node:http.
## What `createServer` hands you `http.createServer(listener)` returns an `http.Server` and registers `listener` for its `'request'` event. Node runs the listener once per HTTP request, possibly several times on one TCP connection when the client keeps it alive. Each call receives two objects, one per direction of the exchange: | Object | Class | Stream role | What is ready when the handler runs | |---|---|---|---| | `req` | `http.IncomingMessage` | `Readable` | request line and headers, already parsed | | `res` | `http.ServerResponse` | `Writable` | nothing sent yet; you decide status, headers and body | On `req` you get `req.method`, `req.url` (the path plus query string, not a full URL), `req.headers` (an object whose names are **lower-cased**) and `req.socket` for connection details. What you do not get is the body. Node's parser hands the handler control as soon as the headers are complete, so a 10 MB upload is still in flight when your code starts. ## Reading the body yourself Because `req` is a `Readable`, the body arrives as a series of `Buffer` chunks, and the server never assembles them for you. The usual steps: 1. Collect the chunks, either with `for await (const chunk of req)` or with `req.on('data', ...)` and `req.on('end', ...)`. 2. Join them once with `Buffer.concat(chunks)`. Converting each chunk to a string separately can split a multi-byte UTF-8 character across two chunks and corrupt it. 3. Decode with `.toString('utf8')`, then `JSON.parse` inside a `try`, because a client can send anything. 4. Decide what to do when the body is too big. Node imposes no body-size limit, so a handler that buffers blindly lets one client fill the heap. Count the bytes as they arrive and stop early. If the handler never reads the body at all, Node cleans up after it: once the response finishes, a request body nobody started consuming is dumped (pulled off the wire and discarded) so the connection can carry the next request. The server still receives every byte of that upload, though, so refusing a large body early means responding and closing the connection rather than ignoring it. ## Writing the response `res` is a `Writable`, and the response is built in order: status line and headers first, body after. - `res.statusCode = 201` and `res.setHeader(name, value)` stage headers that Node sends with the first body write. - `res.writeHead(status, headers)` sets the status and headers in one call. - `res.write(chunk)` sends a piece of the body and returns `false` when the data had to be queued in memory, with `'drain'` emitted once it is safe to write more. - `res.end([data])` finishes the response. The http docs put it plainly: it **must** be called on each response. Forget it and the client hangs until one of its timeouts or the server's gives up. When the whole body goes out in a single `res.end(data)`, Node can set `Content-Length` itself; when you stream with several `res.write()` calls and declare no length, an HTTP/1.1 response normally uses chunked transfer encoding, so you can send a body whose size you do not know in advance. ## Errors live on both streams Both objects are `EventEmitter`s, and stream errors are emitted as `'error'` events. The official guide to the HTTP transaction warns that an `'error'` event on the request with no listener is thrown and can crash the process, so attach a listener (or use `for await`, which turns the error into an exception you can catch). An `async` handler adds a second trap: if it rejects, the server does not catch the rejection, and under Node 24's default `--unhandled-rejections=throw` mode that rejection becomes an uncaught exception. Wrap the body of an async handler in `try`/`catch` and answer with a 4xx or 5xx yourself. ## What a framework adds on top This is why interviewers ask the question: everything a framework does is built on these two streams. Express, for example, wraps the same `req` and `res` and adds: - **routing** by method and path, instead of your own `if` on `req.url`; - **body parsing** with a configurable size limit and content-type checks; - **helpers** such as sending JSON with the right header in one call; - **error handling** that turns a thrown error into a response. Routing and middleware belong with the framework material; the point here is that underneath them is a readable request stream, a writable response stream and an `end()` call that someone must make.
- Why should the chunks be joined with Buffer.concat before decoding, rather than appending chunk.toString() to a string each time?A chunk boundary can fall inside a multi-byte UTF-8 character. Decoding each chunk alone turns the split halves into replacement characters, so the JSON is corrupted for non-ASCII input. Joining the raw `Buffer`s first and decoding once avoids that; `req.setEncoding('utf8')` is the other fix, because it decodes across chunk boundaries.
- What does a Node.js HTTP server do with a request body that the handler responds to but never reads?When the response finishes, Node checks whether anything started consuming the body (`read`, `pipe`, `resume` or a `'data'` listener). If nothing did, it dumps the rest: the bytes are read off the socket and discarded so a kept-alive connection can serve its next request. The upload is still received in full, so to refuse a huge body, respond and destroy the connection instead.
- Thinks req.body exists on a plain node:http request
- Assumes the whole body is available when the handler starts
- Converts every chunk to a string and concatenates the strings
- Forgets res.end() and wonders why clients hang
- Believes Node caps request body size by default
- Leaves an async handler without try/catch