HTTP clients and agents
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Read a native HTTP response
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});import { Agent, get } from 'node:http';function getText(url,agent){return new Promise((resolve,reject)=>{ const req=get(url,{agent,signal:AbortSignal.timeout(2000)},res=>{ let text='';res.setEncoding('utf8');res.on('data',c=>{text+=c;});res.on('end',()=>resolve({text,reused:req.reusedSocket}));res.on('error',reject); });req.on('error',reject);});}await withServer((q,r)=>r.end('stock'),async base=>{const agent=new Agent({keepAlive:true,maxSockets:1});try{console.log((await getText(base,agent)).text);}finally{agent.destroy();}});Run:
node main.mjsExpected stdout:
stockExit status: 0. Expected stderr: empty.
How it works
http.get is a shortcut for GET that ends the outgoing request automatically. http.request requires an explicit end when the body is complete. A response body is readable and must be consumed or canceled; otherwise connection reuse can be affected. A keep-alive agent can retain an idle socket; maxSockets limits active sockets per origin for this agent. The examples use tiny fixed responses and destroy the custom agent in finally. Reuse depends on both peers, timing and protocol; it is not guaranteed for every request.
Observe reuse on sequential local requests
import { createServer } from 'node:http';import { once } from 'node:events';async function withServer(handler, use) { const server = createServer({ headersTimeout: 2000, requestTimeout: 2000 }, handler); server.listen(0, '127.0.0.1'); await once(server, 'listening'); try { await use(`http://127.0.0.1:${server.address().port}`); } finally { await new Promise(resolve => { server.close(resolve); server.closeAllConnections(); }); }}const localFetch = (url, options = {}) => fetch(url, { ...options, redirect: 'error', signal: options.signal ?? AbortSignal.timeout(2000)});import { Agent, get } from 'node:http';function getText(url,agent){return new Promise((resolve,reject)=>{ const req=get(url,{agent,signal:AbortSignal.timeout(2000)},res=>{ let text='';res.setEncoding('utf8');res.on('data',c=>{text+=c;});res.on('end',()=>resolve({text,reused:req.reusedSocket}));res.on('error',reject); });req.on('error',reject);});}await withServer((q,r)=>r.end('ok'),async base=>{const agent=new Agent({keepAlive:true,maxSockets:1});try{const a=await getText(base,agent);const b=await getText(base,agent);console.log(a.reused,b.reused);}finally{agent.destroy();}});Run:
node main.mjsExpected stdout:
false trueExit status: 0. Expected stderr: empty.
Common mistake
An HTTP response with status 404 is not automatically a transport error. Do not confuse a request timeout notification with cancellation; use a signal or explicitly destroy the request. Avoid accepting arbitrary outbound destinations.
Practice
Change the agent to keepAlive:false and compare the observed reuse result. Explain why the server may choose to close a connection anyway.
Further reading: Authoritative source 1. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP clients and agents — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What manages reusable sockets for native HTTP requests?
What is required after preparing a request with http.request?
Does a keep-alive agent guarantee socket reuse?