Every page, image and API call on the web travels over HTTP, and a Node server is a program that speaks it. This lesson shows what the conversation looks like before you write any server code.
HTTP is a request and response protocol. A client, such as a browser, a phone app or curl, opens a connection and sends a request. The server sends back one response and, if the connection is kept open, waits for the next request. The server never speaks first. Each request is handled on its own, which is why HTTP is called stateless: nothing in the protocol makes the server remember who you were a moment ago.
A request has three parts. The request line holds the method, the target and the version, for example GET /menu HTTP/1.1. Then come headers, one Name: value pair per line, that describe the request. A blank line ends the headers. After it comes an optional body, such as the JSON of an order. A response is the same shape: a status line with a three-digit code, headers, a blank line and a body.
Here is a server with three behaviours and the raw exchange for one request. The server is a small node:http program. curl -v prints every line it sends with > and every line it receives with <.
Real output. The Date header changes on every run.
The first four lines starting with > are the request. Host says which site the client wants, which matters because one server can host many. User-Agent names the client program and Accept says which content types it can take. The lines starting with < are the response. The status line says 200 OK. Content-Type tells the client how to read the body, and Content-Length: 17 says the body is 17 bytes, which is the length of the text plus its newline. Connection: keep-alive and Keep-Alive: timeout=5 say the connection stays open for five idle seconds, a point a later lesson picks up.
Animated sceneOne request, one response, then another0:16
Watch for the connection staying open after the first response
Read it as steps
The client sends a request line and headers, the server replies, and the same connection serves a second request.
The second exchange in the scene is the same pattern with a different method, sent on the connection the first one left open. Each request still carries its own request line and headers, because HTTP keeps no state between them, but only the first paid for opening the connection. The last lesson of this chapter measures that reuse and shows what it costs a server when it shuts down.
Methods and status codes
The method says what the client wants to do. The status code says how it went. Both are small vocabularies, and knowing them well makes an API predictable.
Method
Meaning
Safe
Idempotent
GET
Read a resource
Yes
Yes
POST
Create or run an action
No
No
PUT
Replace a resource
No
Yes
DELETE
Remove a resource
No
Yes
GET
MeaningRead a resource
SafeYes
IdempotentYes
POST
MeaningCreate or run an action
SafeNo
IdempotentNo
PUT
MeaningReplace a resource
SafeNo
IdempotentYes
DELETE
MeaningRemove a resource
SafeNo
IdempotentYes
RFC 9110, the HTTP standard, defines both columns. A safe method is one whose meaning is read-only, so a client can call it without changing anything. An idempotent method has the same effect on the server whether you send it once or ten times. That matters when a client retries after a timeout: repeating a DELETE is harmless, repeating a POST can create two orders.
Range
Meaning
Examples
2xx
It worked
200 OK, 201 Created, 204 No Content
3xx
Go somewhere else
301, 304 Not Modified
4xx
The client made a mistake
400, 404, 405, 413, 415
5xx
The server failed
500, 503
The server above returned 201 for a POST to /orders and 404 for anything it did not know. Here are the real status codes it produced for four requests.
text
GET /menu -> 200
POST /orders -> 201
GET /orders -> 404
GET /chai -> 404
The request GET /orders returned 404 even though a POST /orders route exists. A better answer is 405, which says the path exists but not for that method. Building that is the third lesson.
Check yourself
In the raw exchange, how does the client know how many bytes of body to read?
The Content-Length: 17 header gives the body size in bytes.
Without it a server can send the body in chunks, as the echo server in the next lesson does with Transfer-Encoding: chunked.
Why is it safe for a client to retry a timed-out GET or DELETE, but risky to retry a POST?
Both GET and DELETE are idempotent, so repeating them has the same effect as sending once.
POST is not idempotent, so a retry can repeat the action, for example creating a second order.
What do the first digit of a status code and the code 404 tell you?
The first digit gives the class: 2xx success, 3xx redirect, 4xx client error, 5xx server error.
404 means the server does not know that resource, which is a client-side problem, so it is in the 4xx class.
Term
Meaning
Request line
The first line of a request: method, target and HTTP version.
Header
A Name: value line that describes a request or response.
Safe method
A method whose meaning is read-only, such as GET.
Idempotent method
A method with the same effect when sent once or many times.
Part 2 · createServer, request and response
Two objects, one callback
A web server in Node is a function that receives a request object and fills in a response object. The node:http module gives you both.
http.createServer(listener) returns a server, and listener is called once for every request with two arguments. The first, req, is an IncomingMessage that carries what the client sent. The second, res, is a ServerResponse that you use to answer. The server starts accepting connections when you call server.listen(port, host). Binding to 127.0.0.1 makes it reachable only from the same machine, which is the safe choice while you are developing.
Property or method
What it gives you
req.method
The method as an upper-case string, such as GET.
req.url
The target of the request line: the path and the query string, not the host.
req.headers
An object of headers. Names are always lower case.
req.httpVersion
The protocol version, for example 1.1.
res.statusCode
The status code, 200 unless you change it.
res.setHeader(name, value)
Queues a header to send with the response.
res.writeHead(status, headers)
Sends the status line and headers now, merging any set with setHeader.
res.end(body)
Sends the last piece of the body and finishes the response.
Both objects are streams
req is a readable stream of the request body, and res is a writable stream for the response body. The consequence is that everything you learned about streams applies: you can iterate req with for await, and you can pipe a file straight into res.
This echo server shows both sides. For /echo it sends the request body straight back with pipeline, so the body is never held in memory as a whole. For any other URL it replies with a JSON description of the request it received.
The try around pipeline is not decoration. If a client disconnects halfway through an upload, pipeline rejects. With the try removed, a test client that sent half a body and hung up crashed the whole process with Error: aborted and code ECONNRESET, an unhandled rejection. With the try in place, the same test logged one line and the server kept running.
text
echo stopped: ECONNRESET
The server log after a client sent half of a 100-byte body and closed the connection.
The program was started in the background on port 55611, and two requests were sent with curl. The first adds a custom header and a query string.
Look at url. It is /stalls?floor=2, which is the path with the query string and nothing else. To work with the parts, parse it with the URL class, as the next lesson does. Look at the header names. curl sent X-Fest-Day, and the server reports it as x-fest-day. Node lowers the case of every incoming header name, so always read them in lower case: req.headers["content-type"].
The second request posts text to /echo and shows the full response, including the headers Node added by itself.
text
HTTP/1.1200 OK
Content-Type: text/plain
Date: Sun, 22 Nov 202614:10:44 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
two chai please
Printed with `curl -si`; the headers are the real ones.
The body came back unchanged. There is no Content-Length header, because the server started writing before it knew the total size, so Node switched to Transfer-Encoding: chunked. Each piece is sent with its own size and a zero-length piece ends the body. In the first lesson res.end('text') set Content-Length for us, because the whole body was known when the headers were sent.
One more detail from the table. setHeader queues a header and you can change it until the headers are sent. writeHead sends them immediately, and the first call to write or end sends them if you did not. After that point a late setHeader throws an error, so decide on status and headers before the first byte of the body.
Writing the response
The response has its own rules. This script sets a header with setHeader, then calls writeHead with a status and another value for the same header, writes the body in two pieces, and tries to add a header after sending has begun. A fetch call from the same script reads the result.
headersSent after writeHead: true
ERR_HTTP_HEADERS_SENT
202 text/html
setHeader null
<p>first</p><p>second</p>
Real run on port 55611.
Three things follow from the output. writeHead merged with the earlier setHeader: X-Source arrived, and for Content-Type the value given to writeHead won, so the client saw text/html. After writeHead, res.headersSent was true, and the late setHeader threw ERR_HTTP_HEADERS_SENT; the header x-late never reached the client. And write can be called many times before end, so the client received <p>first</p> and <p>second</p> as one body.
The status code defaults to 200, and a different one needs res.statusCode = 404 or writeHead(404, ...). A redirect is a 3xx status plus a Location header, such as writeHead(302, { Location: "/menu" }). The status text, OK or Not Found, is filled in for you.
Check yourself
A request arrives with the header X-Fest-Day: 2. How do you read it in the handler?
Use req.headers['x-fest-day'], because Node lower-cases header names.
The value is the string '2', not a number.
Why did the echo response in the run use Transfer-Encoding: chunked and no Content-Length?
The handler began sending the body before the total size was known, because it piped the request into the response.
Chunked encoding sends the body in pieces, each with its own size.
What do you get from req.url for a request to http://localhost:3000/stalls?floor=2?
The string /stalls?floor=2: the path and the query string.
The host and the scheme are not part of it, so use the URL class to split the path from the query.
Part 3 · Routing by hand
A route table
A route pairs a method and a path with a handler function. Routing is the decision, for each request, of which handler runs. Frameworks hide this decision, and writing it once by hand shows what they do.
There are three outcomes, and they have different status codes. If the path and the method both match a route, the handler runs. If the path matches nothing, the answer is 404 Not Found. If the path exists but not for this method, the answer is 405 Method Not Allowed. RFC 9110 says a 405 response must carry an Allow header that lists the methods the resource does support, so the client learns what it may send instead.
The code uses an object as the route table, keyed by path, with one handler per method inside. The helper send writes a JSON response so each handler stays short. The first block is the helper and the data. The second holds the route table and the server.
Start at the bottom. new URL(req.url, 'http://localhost') parses the target. The second argument is a dummy base, needed because req.url has no host. After that, url.pathname is the path alone and url.searchParams holds the query. The route is found by routes[url.pathname]. If there is none, it returns 404. Otherwise route[req.method] finds the handler, and if that is missing it returns 405 with an Allow header built from the method names the route does have.
A subtle point about return send(...): the return stops the function, so the handler below it cannot run after an error reply. Forgetting it is a common bug that ends with the server trying to send two responses.
One gap is worth knowing. RFC 9110 expects a general-purpose server to answer HEAD, which is GET without the body, wherever it answers GET. This table has no HEAD entries, so a HEAD request for /stalls got 405 with Allow: GET, POST in a run. Frameworks add HEAD for you; a hand-written router has to map it to the GET handler and skip the body.
Trying every outcome
Animated sceneThree requests, three outcomes0:18
GET /stalls: the path and the method both match
Read it as steps
A match runs its handler, an unknown path gets 404, and a wrong method gets 405 with Allow.
The scene mirrors the run below. The curl lines are real, and only the interesting headers and the body are kept from each response.
text
$ curl -i -X GET localhost:55612/stalls
HTTP/1.1200 OK
[{"id":1,"name":"Chai"},{"id":2,"name":"Vada Pav"}]
$ curl -i -X GET localhost:55612/stalls?q=vada
HTTP/1.1200 OK
[{"id":2,"name":"Vada Pav"}]
$ curl -i -X POST localhost:55612/stalls
HTTP/1.1201 Created
Location: /stalls/3
{"id":3}
$ curl -i -X DELETE localhost:55612/stalls
HTTP/1.1405 Method Not Allowed
Allow: GET, POST
{"error":"method not allowed"}
$ curl -i -X GET localhost:55612/nothing
HTTP/1.1404 Not Found
{"error":"not found"}
Real run on port 55612; status line, Allow, Location and body shown.
The POST returned 201 Created with a Location header pointing at the new resource, which is the convention for creation. The wrong-method request received 405 and Allow: GET, POST, the exact methods in the table.
Paths with parameters
A table keyed by exact path breaks as soon as a path contains data, such as /stalls/3 for stall number 3. A path parameter is a variable segment in a route, usually written with a colon: /stalls/:id. Frameworks match these for you. The function below is a minimal version that splits both strings on / and compares segment by segment.
js
function match(pattern, pathname) {
const want = pattern.split('/');
const got = pathname.split('/');
if (want.length !== got.length) returnnull;
const params = {};
for (let i = 0; i < want.length; i++) {
if (want[i].startsWith(':')) params[want[i].slice(1)] = got[i];
elseif (want[i] !== got[i]) returnnull;
}
return params;
}
console.log(match('/stalls/:id', '/stalls/3'));
console.log(match('/stalls/:id', '/stalls'));
console.log(match('/stalls/:id/menu/:item', '/stalls/3/menu/dosa'));
console.log(match('/stalls/:id', '/shops/3'));
console.log(match('/stalls/:id', '/stalls/3/'));
const id = Number(match('/stalls/:id', '/stalls/abc').id);
console.log(Number.isInteger(id) && id > 0 ? 'ok' : 'answer 400');
A match returns an object with the captured values, and anything else returns null. The third call captured two parameters at once. The fifth call shows that /stalls/3/ with a trailing slash does not match /stalls/:id, because it has one more segment. Decide whether your API treats those as the same and normalise on purpose, since many clients add or drop trailing slashes.
Captured values are always strings. The last two lines convert the id from /stalls/abc with Number and check that it is a positive integer, which it is not, so the right reply is 400. A request for a stall that does not exist is a different case: that one is 404. Keeping the two apart tells a client whether its request was malformed or just aimed at something that is not there.
Check yourself
What is the difference between 404 and 405 in this router?
404 means the path is not in the table at all.
405 means the path exists but has no handler for that method, and the reply must list the allowed methods in an Allow header.
Why does the router parse req.url with new URL(req.url, 'http://localhost')?
req.url holds only the path and the query string, and the URL class needs a base to parse it.
It then gives pathname for routing and searchParams for the query, without splitting strings by hand.
A handler throws an error after the router has already called send(res, 404, ...). What went wrong in the code?
The return was missing, so the function carried on after sending the reply.
Sending a second response on the same request causes an error, so always return send(...).
Part 4 · Reading a JSON body safely
The body arrives in pieces
When an app places an order it sends a JSON body, and your server has to read it without trusting it. The body is not available as a value when the handler starts. It arrives in chunks on the req stream, and you decide when you have all of it.
The simple recipe is to collect the chunks, join them and call JSON.parse. The recipe is dangerous in its simple form because the client chooses how much to send. A client that sends several gigabytes would fill your memory, and one bad request could end the process. So a body reader needs a limit on the number of bytes, and it needs clear answers for each way a request can be wrong.
Problem
Status
Meaning
Not JSON syntax
400 Bad Request
The body cannot be parsed.
Wrong Content-Type
415 Unsupported Media Type
The format is not one this route accepts.
Too many bytes
413 Content Too Large
The body is bigger than the limit.
The function below enforces all three. Its errors carry a status property, so one catch in the handler can turn any of them into a reply.
The reader
js
class HttpError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}
asyncfunction readJson(req, limit) {
consttype = req.headers['content-type'] ?? '';
if (!type.startsWith('application/json')) {
thrownew HttpError(415, 'send application/json');
}
const chunks = [];
let size = 0;
forawait (const chunk of req) {
size += chunk.length;
if (size > limit) thrownew HttpError(413, 'body too large');
chunks.push(chunk);
}
try {
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
} catch {
thrownew HttpError(400, 'body is not valid JSON');
}
}
body.mjs, lines 3 to 27
The checks run in order. First the content type, which costs nothing and rejects the wrong format before any bytes are read. Then for await (const chunk of req) reads the stream. Each chunk is a Buffer, and chunk.length is its size in bytes, so size is a running total that is compared with the limit at every step. The reader stops as soon as the total passes the limit, so a large upload never fills memory. Only after all chunks are in does it join them, decode as UTF-8 and parse.
Counting bytes matters more than counting characters here, as the earlier lesson on buffers showed. The limit protects memory, and memory is measured in bytes.
The handler wraps the call in try and catch. An error with a status becomes that status, and anything else is treated as a 500, because it is a fault in our own code, not the client's. Five requests were sent to the server running with a limit of 1,024 bytes. The fourth carried a body of about 5,000 bytes and the fifth one of about 5 MB.
text
{"received":{"item":"dosa","qty":2}} -> 201
{"error":"body is not valid JSON"} -> 400
{"error":"send application/json"} -> 415
{"error":"body too large"} -> 413
{"error":"body too large"} -> 413
Real run on port 55613. The status code is printed after each body.
Each outcome has its own status. The last two requests were refused with 413 as soon as the reader had counted past 1,024 bytes, and curl still received the reply for the 5 MB body on this machine. That is not guaranteed everywhere: when a server answers before the upload ends, a client that is still sending can see the connection reset before it reads the reply, so clients should watch for an early response while they upload.
RFC 9110 names 413 Content Too Large. Its older name was Payload Too Large, and that is still the text Node puts in the status line: the run printed HTTP/1.1 413 Payload Too Large for the oversized body. Clients act on the number, not on the text, so the difference is harmless.
Framework middleware such as express.json() does most of this for you: a byte limit, 100 KB unless you set its limit option, and a 400 for bad JSON. It differs on the content type. A request that is not JSON is skipped and left without a parsed body rather than refused with 415, so a route that must have JSON still checks for it.
Valid JSON is not a valid order
Parsing success only proves the text is JSON. JSON.parse accepts any JSON value, and an order handler expects a plain object. Five bodies, all valid JSON, show how different the results are.
js
const bodies = ['{"item":"dosa"}', 'null', '42', '[]', '"dosa"'];
for (const text of bodies) {
const value = JSON.parse(text);
const plain = value !== null && typeof value === 'object'
&& !Array.isArray(value);
console.log(text.padEnd(16), typeof value, 'plain object:', plain);
}
Only the first is a plain object. null and arrays report typeof as object, which is why the check also excludes them. A handler that reads order.item on null would throw a TypeError and return a 500 for what is really a 400 mistake by the client. After parsing, check the shape and the type of each field, and answer 400 or 422 with a message that names the field. The chapter on production APIs builds this validation properly.
There is also a cheap early check. A client may send a Content-Length header that says how big the body will be. If it is already over your limit you can reply 413 without reading a byte. Do not rely on it alone: the header can be absent when the body is chunked, and it can be wrong, so the byte count while reading stays.
Check yourself
Why does the body reader count bytes while it reads instead of parsing at the end?
The client chooses how much to send, so an unchecked reader can be made to use all the memory.
Counting as chunks arrive lets the server stop at the limit and reply 413.
A client posts {"item": as the body with the right content type. Which status does the server return, and why?
400, because the body is not valid JSON and JSON.parse fails.
The reader turns that failure into an HttpError with status 400.
Why is the Content-Type check done before the body is read?
It is free and rejects the wrong format with 415 without reading any bytes.
Reading a large body only to reject it afterwards wastes time and memory.
Part 5 · Serving static files
Files over HTTP
A web page needs HTML, style sheets and images, and a small server can send them straight from a folder. The two things to get right are what you tell the browser about each file, and which files you are willing to send.
Each file needs a content type, also called a MIME type, which tells the browser how to treat the bytes: text/html to render, text/css to apply, image/png to draw. Servers choose it from the file extension, using a lookup table. Anything not in the table can be sent as application/octet-stream, which means "unknown bytes".
A file can be large, so it should be streamed to the response rather than read whole. The previous lessons gave you the tools: createReadStream for the source and pipeline to join it to res, which also closes the file if the client disconnects part way. stat gives the size for Content-Length and tells you whether the path is a file at all.
The third piece is a safety check. The path in the URL is chosen by the client, and if you append it to a folder name without care, a client can climb out of the folder.
Path traversal
Path traversal is an attack where the request path contains .. segments, or an encoded form of them, so that the final path points outside the public folder. The goal is to read files that were never meant to be public, such as a configuration file or a private key.
req.url arrives exactly as the client sent it. Parsing it with the URL class removes literal .. segments, and their encoded form %2e%2e, but an encoded slash slips through. This script shows what the parser does with three spellings and what is left after decoding.
js
const show = (p) => new URL(p, 'http://x').pathname;
console.log(show('/a/../secret.txt'));
console.log(show('/%2e%2e/secret.txt'));
console.log(show('/..%2fsecret.txt'));
console.log(decodeURIComponent(show('/..%2fsecret.txt')));
The first two are normalised to /secret.txt by the parser. The third keeps ..%2f untouched, because %2f is an encoded slash, and decoding it produces /../secret.txt. A server that decodes the path and joins it to the public folder without a check will follow that path out of the folder. The run below uses such a server: the guarded server on the next page with its two checking lines removed, serving a folder called public that sits next to a file secret.txt. The first request uses the third spelling. The second uses %5c, an encoded backslash, which Windows treats as a folder separator.
Real run of the unguarded server. `--path-as-is` stops curl tidying the path.
The secret file was served both times. The fix is short and does not try to spot bad patterns. It resolves the full path first and then checks the result.
path.resolve(ROOT, '.' + name) builds an absolute path and removes any ... The check file.startsWith(ROOT + path.sep) then asks the only question that matters: is the final location inside the public folder? Adding path.sep stops a folder named public-old from passing a plain prefix test. Everything outside gets 403 Forbidden. A path that cannot be decoded, like %zz, makes decodeURIComponent throw, and that is caught and answered with 400.
The check compares path text, not the disk. A symbolic link inside public that points elsewhere would still be followed. Keep links out of a public folder, or compare fs.realpath of the file against the root when links are possible.
Trying it
Seven requests, including three traversal spellings.
Real run on port 55614; status line, Content-Type and body shown.
The home page and the style sheet came back with the right content types. A missing file gave 404, all three traversal attempts gave 403, and the bad escape gave 400. The check works on the resolved path, so it did not matter which spelling the attacker used.
Production static files
This server is for learning. The guarded version sends no caching headers and has no range requests or compression. In production, static files are usually served by a CDN or a reverse proxy in front of the app.
Conditional requests and 304
A browser keeps a copy of each file it downloaded. Downloading the style sheet again on every visit wastes time, and never checking would show stale pages. A conditional request is the middle path: the browser asks the server whether its copy is still current.
The server gives each version of a file a label called an ETag, such as a hash or a size and time stamp. The browser stores it, and on the next request sends it back in an If-None-Match header. If the label still matches, the server replies 304 Not Modified with no body, and the browser uses its stored copy. If the file changed, the server sends a normal 200 with the new content and a new label. The header Cache-Control: no-cache means "keep a copy, but ask me before you use it", which is what makes the check happen on every visit.
Real run on port 55615. The Date headers are left out, and the file was edited between the last two requests.
The first request returned the file with its label. The second sent that label back and received a 304 with an empty body, which saves the transfer of the file. After the file was edited, the same label no longer matched, so the server sent a 200 with the new content and a new label. A label built from the size and the modified time is enough for a demonstration. Real servers often hash the content, and web frameworks and CDNs do this for you, which is why you rarely write it by hand.
Check yourself
Why does the guard resolve the path first and then check it, instead of looking for .. in the URL?
There are many ways to write a traversal, such as encoded slashes, and a text search can miss one.
The resolved path shows where the file really is, so one startsWith check covers every spelling.
Why is the check file.startsWith(ROOT + path.sep) and not file.startsWith(ROOT)?
A sibling folder such as public-old starts with the same text as public.
Adding the separator means the path must be inside the folder, not merely share a prefix.
A teammate guards the static server by rejecting any URL that contains ../. On Windows, a request for /..%5csecret.txt still returns the secret file. Why, and what is the fix?
%5c decodes to a backslash, so the decoded path never contains ../, and Windows treats the backslash as a separator, so the path leaves the folder.
Resolve the path against the root and check that the result starts with the root plus path.sep; the guarded server answered that request with 403.
Part 6 · Keep-alive, timeouts and fetch
Connections are reused
Opening a TCP connection takes a round trip before a single byte of HTTP is sent, so clients try not to do it for every request. Keep-alive means leaving the connection open after a response so the next request can use it. HTTP/1.1 does this by default, and the headers in the first lesson showed it: Connection: keep-alive and Keep-Alive: timeout=5. On the client side, the default agent of node:http has kept connections alive since Node 19.
The script below makes three requests with the default settings of the node:http client, then three with agent: false, which asks for a fresh connection each time. The server notes the client port of each request, because a new connection has a new port.
js
import { createServer, get } from'node:http';
const ports = [];
const server = createServer((req, res) => {
ports.push(req.socket.remotePort);
res.end('ok');
});
awaitnew Promise((ok) => server.listen(55616, '127.0.0.1', ok));
function call(options) {
returnnew Promise((done) => {
get('http://127.0.0.1:55616/', options, (res) => {
res.resume();
res.on('end', done);
});
});
}
for (let i = 0; i < 3; i++) await call({});
console.log('default agent :', new Set(ports).size, 'connection(s)');
ports.length = 0;
for (let i = 0; i < 3; i++) await call({ agent: false });
console.log('agent: false :', new Set(ports).size, 'connection(s)');
server.close();
Three requests used one connection with the default agent, and three connections without it. In a real service the effect is large: a client that makes many calls to the same server saves a connection set-up on nearly every one, and the server holds fewer sockets.
Timeouts a server needs
A connection that stays open costs the server memory, and a client that sends slowly can hold one open for a long time. Node's HTTP server has several timers to limit that. They have defaults, and this script prints them for this version.
Time to receive the whole request. Past it the server replies 408 and closes.
headersTimeout
60000 ms
Time to receive the complete headers. Same 408 and close.
keepAliveTimeout
5000 ms
How long an idle connection waits for another request.
keepAliveTimeoutBuffer
1000 ms
Extra time added to the keep-alive timeout before the socket is dropped.
timeout
0
No socket inactivity timeout by default.
maxRequestsPerSocket
0
No limit on requests per connection.
The docs advise setting a non-zero requestTimeout and headersTimeout when the server faces the internet without a reverse proxy, to protect against clients that send very slowly on purpose. The defaults already do that for the two request timers.
Shutting down without cutting people off
A server that must stop, for a deploy or a restart, should finish the requests it has and refuse new ones. server.close() does the refusing: it stops accepting connections and, since Node 19, closes the connections that are idle at that moment. In-flight requests continue. The callback runs when every connection is gone.
Here the handler takes 300 ms to answer. The script waits until the request has arrived, calls server.close(), and times the callback. The script takes the keep-alive timeout of the server as an argument, and it was run three times with different values.
keepAliveTimeout 5000:
in-flight reply: done
close callback after about 4318 ms
keepAliveTimeout 2000:
in-flight reply: done
close callback after about 1321 ms
keepAliveTimeout 1000:
in-flight reply: done
close callback after about 307 ms
Real runs on this machine. Times vary.
The in-flight reply still arrived. But the close callback did not run when the request finished. It waited about four seconds, and the wait fell as the keep-alive timeout fell. The connection was busy when close() ran, so it was not closed then. After the answer it became idle and stayed open, and close could not complete until it went. Here the client ended it: Node's HTTP client drops an idle connection one second before the timeout the server advertises (its agentKeepAliveTimeoutBuffer), so each wait was about 300 ms plus the timeout minus one second. A client that never hangs up holds the server longer. In a run with a raw TCP client and the default 5,000 ms, the callback came after 6,326 ms: the server's own idle timer is keepAliveTimeout plus keepAliveTimeoutBuffer, 6 seconds, counted from the 300 ms reply. The fix is to tell the client to close the connection when the answer goes out during shutdown, with the header Connection: close.
js
import { createServer, get } from'node:http';
let arrived;
let closing = false;
const seen = new Promise((ok) => (arrived = ok));
const server = createServer((req, res) => {
arrived();
setTimeout(() => {
if (closing) res.setHeader('Connection', 'close');
res.end('done');
}, 300);
});
awaitnew Promise((ok) => server.listen(55617, '127.0.0.1', ok));
const slow = new Promise((done) => {
get('http://127.0.0.1:55617/', (res) => {
res.resume();
res.on('end', done);
});
});
await seen;
closing = true;
const t0 = performance.now();
server.close(() => {
const ms = Math.round(performance.now() - t0);
console.log('close callback after about', ms, 'ms');
});
await slow;
text
close callback after about 316 ms
Now the callback ran as soon as the response ended, a few milliseconds after the 300 ms the handler needed. The server also has closeIdleConnections() and closeAllConnections(). The first closes connections that are idle at that moment, and the second also cuts requests in flight, so keep that for a final deadline. One more result from a test: calling close() right after sending a request on a reused connection made the client receive ECONNRESET, probably because the server closed what it saw as an idle connection before it had read the request.
text
first call : ok
second call: ECONNRESET
A second call sent right before `close()`. Clients should retry idempotent requests.
fetch as a client
Your server will call other services, and Node has the same fetch function as browsers. It has been a global since Node 18 and is stable since Node 21. It is built on the undici HTTP client. It returns a promise of a Response.
Two traps catch beginners. First, fetch does not reject on a 404 or 500. The promise resolves, and you must check res.ok or res.status yourself. It rejects only when no response came at all, such as a refused connection. Second, there is no timeout unless you add one. AbortSignal.timeout(ms) gives you one.
The first call succeeded and res.json() parsed the body. The second returned a 404 with ok false and no exception. The slow endpoint was cut at 100 ms, and the error was named TimeoutError. The last call went to a closed port. It rejected with a TypeError whose cause held the system error ECONNREFUSED. Handle all three outcomes: a bad status, a timeout and a failed connection.
Check yourself
In the keep-alive run, why did three requests with agent: false use three connections?
That option gives each request its own connection that is not reused.
The default agent keeps the connection open, so the three requests shared one.
await fetch(url) returned without throwing for a 404. How do you detect the failure?
fetch rejects only when no response arrives.
Check res.ok or res.status after the promise resolves.
Why did server.close() take several seconds to finish in the first shutdown run?
The connection was busy when close() ran, so it was not closed; after the response it stayed open and idle until a keep-alive timer ended it, here the client's.
Sending Connection: close on responses during shutdown ends the connection with the response.
Term
Meaning
Keep-alive
Leaving a connection open so later requests can reuse it.
Content type
The header that tells a client how to read a body.
Path traversal
Using .. in a path to reach files outside a folder.
In-flight request
A request the server has received and not yet answered.