agent-base — Custom HTTP Agent Helper
Helps users create custom http.Agent subclasses based on the agent-base module, for scenarios such as HTTP request proxying, custom socket connections, etc.
Trigger Scenarios
Use when the user needs to write HTTP/HTTPS/SOCKS/PAC proxies, custom HTTP connection logic, or extend http.Agent.
Module Overview
agent-base wraps an ordinary function into an http.Agent instance. It is an abstract class that requires defining the connect(req, opts) method to create the underlying Socket.
connect()can return anyDuplexstream, or anotherhttp.Agentinstance to delegate the requestconnect()can be anasyncfunctionopts.secureEndpointis used to distinguish between HTTP / HTTPS
Quick Start
import * as net from 'net';
import * as tls from 'tls';
import * as http from 'http';
import { Agent } from 'agent-base';
class MyAgent extends Agent {
connect(req, opts) {
if (opts.secureEndpoint) {
return tls.connect(opts);
} else {
return net.connect(opts);
}
}
}
const agent = new MyAgent({ keepAlive: true });
http.get('http://nodejs.org/api/', { agent }, (res) => {
console.log('"response" event!', res.headers);
res.pipe(process.stdout);
});
Workflow
- Identify user requirements: Pure HTTP/HTTPS proxy? SOCKS? PAC? Or custom routing?
- If a mature solution exists, prioritize recommending community subclasses (see below)
- If custom implementation is needed, write the
connect()method based on theAgentabstract class - Provide complete, runnable TypeScript/JavaScript examples
Proxy Details
See references/proxy-details.md, which includes:
http-proxy-agent— HTTP endpoint proxyhttps-proxy-agent— HTTPS endpoint proxypac-proxy-agent— PAC file proxysocks-proxy-agent— SOCKS proxy- Selection guide and comparison of each subclass
