HTTP

new http.Agent()

Controls connection reuse and limits for native HTTP client requests. An application-owned agent should be reused across requests and destroyed when no longer needed. Its socket cap is not a global cap on application work. Tested on Node.js 22.16.0. Example output (one line per entry): ["false", "true"].

Formal Syntax & Structure

nodejs syntaxnodejs
new http.Agent([options])

Parameters & Attributes

NameTypeDescription
optionsobjectFor example keepAlive and maxSockets.

Return Value

http.Agent

Connection manager.

Working Example

Example Snippetnodejs
import http from 'node:http';const server = http.createServer((req, res) => res.end('ok'));await new Promise(r => server.listen(0, '127.0.0.1', r));const url = 'http://127.0.0.1:' + server.address().port;try {    const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });    try {        const get = () => new Promise((resolve, reject) => { const q = http.get(url, { agent }, r => { r.resume(); r.on('end', () => resolve(q.reusedSocket)); r.on('error', reject); }); q.on('error', reject); });        console.log(await get());        await new Promise(r => setImmediate(r));        console.log(await get());    }    finally {        agent.destroy();    }}finally {    server.closeAllConnections();    await new Promise(r => server.close(r));}
Node.js Reference