Node.js HTTP Server, Headers, AbortSignal, and Native fetch
Nothing is parsed for you: an unread body stalls the socket, and headers cannot change after the first write. fetch resolves on 404, and AbortSignal is the timeout mechanism.

Quick Summary
node:http gives you a server whose request and response objects are streams. Nothing is parsed for you: no body, no cookies, no JSON. res.writeHead() sends status and headers, req is a readable stream you must consume or the socket stalls.
Native fetch (undici, global since Node 18) is the client half. It resolves on any HTTP status — 404 and 500 are successful fetches — and rejects only on transport failure, as TypeError: fetch failed with the real error in .cause.
Cancellation is AbortSignal on both sides. AbortSignal.timeout(ms) for a deadline, AbortSignal.any([...]) to combine, and req.signal on the server to notice a client that hung up before you finish the response.
Basic Syntax and Core Signatures
import http from 'node:http';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
const server = http.createServer({
keepAliveTimeout: 72_000,
headersTimeout: 30_000,
requestTimeout: 120_000,
maxHeaderSize: 16 * 1024,
}, async (req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
if (req.method === 'POST' && url.pathname === '/items') {
const chunks = [];
for await (const chunk of req) chunks.push(chunk); // must consume
const body = Buffer.concat(chunks).toString('utf8');
res.writeHead(201, {
'content-type': 'application/json',
'content-length': Buffer.byteLength(JSON.stringify({ ok: true })),
});
return res.end(JSON.stringify({ ok: true }));
}
res.statusCode = 200;
res.setHeader('content-type', 'text/plain; charset=utf-8');
res.setHeader('cache-control', 'no-store');
res.end('ok');
});
server.listen(0, () => console.log('port', server.address().port));
// Graceful shutdown
process.on('SIGTERM', () => {
server.close(() => process.exit(0)); // stop accepting
server.closeIdleConnections(); // Node 18.2+
});// fetch: client, with timeouts and an abort signal
const ac = new AbortController();
const signal = AbortSignal.any([ac.signal, AbortSignal.timeout(5_000)]);
try {
const res = await fetch('https://api.example.com/v1/items', {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
body: JSON.stringify({ name: 'x' }),
signal,
redirect: 'follow',
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const data = await res.json();
} catch (err) {
if (err.name === 'TimeoutError') { /* deadline */ }
else if (err instanceof TypeError) console.error(err.cause); // ECONNREFUSED, …
}Key Comparison Table
| Task | node:http | native fetch |
|---|---|---|
| Body parsing | Manual | Manual (res.json()) |
| Streaming request body | req readable | body with duplex: 'half' |
| Status handling | You set it | Resolves on 4xx/5xx |
| Timeout | requestTimeout, headersTimeout | AbortSignal.timeout |
| Connection pool | Agent per host | undici dispatcher |
| Retries | None | None (write them) |
| Server option | Default | What it controls |
|---|---|---|
keepAliveTimeout | 5 s | Idle keep-alive socket lifetime |
headersTimeout | 60 s | Time allowed to receive headers |
requestTimeout | 300 s | Whole request lifetime (Node 18+) |
maxHeaderSize | 16 KiB | Header block limit |
server.timeout | 0 | Socket inactivity, off by default |
AbortSignal source | Available since | Use |
|---|---|---|
new AbortController() | Node 15 | Manual cancel |
AbortSignal.timeout(ms) | Node 17.3 | Deadline |
AbortSignal.any([...]) | Node 20.3 | Combine deadline and cancel |
req.signal | modern LTS | Client disconnected |
Practical Edge Cases and Deep Dives
1. A body that is never consumed
server.on('request', (req, res) => {
if (req.url !== '/upload') return res.end('ok'); // POST body never read
});If the handler responds without reading the request body, Node keeps the remaining bytes in the socket and, depending on the client and keep-alive state, the next request on that connection reads them as a malformed request line — or the socket is destroyed and the client sees a reset. Consume the body (req.resume() is enough if you do not need it) before responding, and call req.destroy() when you intend to reject a large upload early.
2. Headers set after they are sent
res.write('partial');
res.setHeader('x-late', '1'); // ERR_HTTP_HEADERS_SENT
res.writeHead(500); // sameThe first write() (or writeHead(), or end()) flushes the status line and headers; res.headersSent is the check. Streaming handlers that discover an error after the first chunk cannot change the status — the only protocol-correct options are to destroy the response (res.destroy(err)) so the client sees a truncated body, or to send an explicit trailer if the client negotiated them.
3. Content-Length that disagrees with the body
const body = JSON.stringify(payload);
res.setHeader('content-length', body.length); // wrong for non-ASCII
res.end(body); // client hangs waiting for bytesWith Buffer.byteLength correct, the client knows where the response ends; with a short value, it waits for the rest until a timeout; with a long one, it reads into the next response on a keep-alive connection. Omitting Content-Length entirely is safer than guessing: Node sends Transfer-Encoding: chunked and the framing is explicit. Status 204 and 304 must have no body at all, and HEAD responses must not send one either.
4. fetch and the response body you forgot to read
const res = await fetch(url, { method: 'POST', body });
if (!res.ok) return null; // body left unread: socket stays checked outundici keeps a connection until its response body is consumed or cancelled. A hot loop that returns early on non-2xx statuses leaks connections from the pool and eventually throws UND_ERR_CONNECT_TIMEOUT despite the server being healthy. Either read it (await res.text(), await res.arrayBuffer()) or discard it (await res.body?.cancel()), and set an undici.Agent with a deliberate connections count when you need more parallelism:
import { Agent, setGlobalDispatcher } from 'undici';
setGlobalDispatcher(new Agent({ connections: 64, keepAliveTimeout: 10_000 }));5. Aborting on the server side, correctly
server.on('request', async (req, res) => {
const db = pool.query('select * from big');
req.signal.addEventListener('abort', () => db.cancel());
try {
const rows = await db;
if (res.writableEnded) return; // client already gone
res.end(JSON.stringify(rows));
} catch (err) {
res.destroy(err);
}
});req.signal fires when the client disconnects, which is the only reliable way to stop expensive work nobody is waiting for. Checking res.writableEnded (not res.finished) before writing avoids ERR_STREAM_WRITE_AFTER_END noise in logs. For a streaming response, pipeline(source, res) destroys the source automatically when the socket closes.
6. Streaming request bodies with fetch
import { Readable } from 'node:stream';
const body = Readable.from(async function* () {
for await (const chunk of source) yield chunk;
}());
await fetch('https://upload.example.com', {
method: 'PUT',
body,
duplex: 'half', // required for a streaming body
headers: { 'content-type': 'application/octet-stream' },
});A stream body requires duplex: 'half'; without it fetch throws RequestInit: duplex option is required when sending a body. With it, the request uses chunked encoding and no Content-Length, so a server that insists on a declared length rejects it — the workaround is to buffer, which defeats the purpose. For large uploads, http.request or a client that supports resumable uploads is often the better route.
Common Node.js Runtime Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Client hangs on a response | Wrong content-length | Buffer.byteLength, or omit it |
ERR_HTTP_HEADERS_SENT | Header set after first write | Decide headers before writing |
| Next request on a keep-alive socket is garbled | Request body not consumed | req.resume() or read it |
ECONNRESET under load | keepAliveTimeout shorter than the client's idle time | Raise it above the proxy's timeout |
fetch failed with no detail | Transport error wrapped in TypeError | Read err.cause.code |
UND_ERR_CONNECT_TIMEOUT with a healthy server | Unread response bodies leaked connections | Consume or cancel bodies |
RequestInit: duplex option is required | Stream body without duplex: 'half' | Add it |
| Upload rejected as too large | maxHeaderSize/proxy limit, or buffered body | Stream, raise the limit deliberately |
| Server never shuts down on SIGTERM | Open keep-alive connections | closeIdleConnections(), then closeAllConnections() |
| 204 response with a body | res.end(data) on a 204 | End with no data |
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never calls back hangs forever.
Node.js crypto: Hashing, HMAC, AES-GCM, and Random Bytes
Hashing, HMAC, AES-256-GCM and randomness solve different problems. Never reuse a GCM nonce, never hash a password with sha256, and compare secrets with timingSafeEqual.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.