Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNode.js
#Node.js#HTTP#Fetch#Server
3D illustration of a server rack receiving request cards with an abort stop sign cutting a fetch arrow

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

js
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+ });
js
// 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

Tasknode:httpnative fetch
Body parsingManualManual (res.json())
Streaming request bodyreq readablebody with duplex: 'half'
Status handlingYou set itResolves on 4xx/5xx
TimeoutrequestTimeout, headersTimeoutAbortSignal.timeout
Connection poolAgent per hostundici dispatcher
RetriesNoneNone (write them)
Server optionDefaultWhat it controls
keepAliveTimeout5 sIdle keep-alive socket lifetime
headersTimeout60 sTime allowed to receive headers
requestTimeout300 sWhole request lifetime (Node 18+)
maxHeaderSize16 KiBHeader block limit
server.timeout0Socket inactivity, off by default
AbortSignal sourceAvailable sinceUse
new AbortController()Node 15Manual cancel
AbortSignal.timeout(ms)Node 17.3Deadline
AbortSignal.any([...])Node 20.3Combine deadline and cancel
req.signalmodern LTSClient disconnected

Practical Edge Cases and Deep Dives

1. A body that is never consumed

js
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

js
res.write('partial'); res.setHeader('x-late', '1'); // ERR_HTTP_HEADERS_SENT res.writeHead(500); // same

The 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

js
const body = JSON.stringify(payload); res.setHeader('content-length', body.length); // wrong for non-ASCII res.end(body); // client hangs waiting for bytes

With 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

js
const res = await fetch(url, { method: 'POST', body }); if (!res.ok) return null; // body left unread: socket stays checked out

undici 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:

js
import { Agent, setGlobalDispatcher } from 'undici'; setGlobalDispatcher(new Agent({ connections: 64, keepAliveTimeout: 10_000 }));

5. Aborting on the server side, correctly

js
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

js
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

SymptomCauseFix
Client hangs on a responseWrong content-lengthBuffer.byteLength, or omit it
ERR_HTTP_HEADERS_SENTHeader set after first writeDecide headers before writing
Next request on a keep-alive socket is garbledRequest body not consumedreq.resume() or read it
ECONNRESET under loadkeepAliveTimeout shorter than the client's idle timeRaise it above the proxy's timeout
fetch failed with no detailTransport error wrapped in TypeErrorRead err.cause.code
UND_ERR_CONNECT_TIMEOUT with a healthy serverUnread response bodies leaked connectionsConsume or cancel bodies
RequestInit: duplex option is requiredStream body without duplex: 'half'Add it
Upload rejected as too largemaxHeaderSize/proxy limit, or buffered bodyStream, raise the limit deliberately
Server never shuts down on SIGTERMOpen keep-alive connectionscloseIdleConnections(), then closeAllConnections()
204 response with a bodyres.end(data) on a 204End with no data

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.